gpt4 book ai didi

python - 奇怪的时间戳转换

转载 作者:太空宇宙 更新时间:2023-11-03 16:53:53 25 4
gpt4 key购买 nike

我有这些日期

  • 2016-02-26 12:12:12
  • 2016-02-星期五 12:12:12

(这两个日期指的是同一天)

如果我将第一个时间戳转换为时间戳,然后将其转换回可读格式,则它可以工作。

但是,如果我在第二个尝试同样的操作,它不会转换回正确的日期!

这就是我所做的:

sTimestamp = time.mktime(
datetime.datetime.strptime(
"2016-02-26 12:12:12",
"%Y-%m-%d %H:%M:%S")
.timetuple())
print("date from timestamp = " +
datetime.datetime.fromtimestamp(int(sTimestamp))
.strftime('%Y-%m-%d %H:%M:%S'))

sTimestamp = time.mktime(
datetime.datetime.strptime(
"2016-02-friday 12:12:12",
"%Y-%m-%A %H:%M:%S")
.timetuple())
print("date from timestamp = " +
datetime.datetime.fromtimestamp(int(sTimestamp)).
strftime('%Y-%m-%d %H:%M:%S'))

这两行的输出是:

  • 时间戳中的日期 = 2016-02-26 12:12:12
  • 时间戳中的日期 = 2016-02-01 12:12:12

正如您所看到的,第一个返回到 26,但第二个返回到 01,原因未知。顺便说一句,01 是星期一...

有关信息,我正在使用 python 3.4 并且我在 Windows 上。

最佳答案

第一个问题:

(Those two dates refers to the same day)

不,他们没有。第一个是指2016年2月的最后一个星期五;第二个最多指 2016 年 2 月的某个星期五。

此外,strptime 旨在与数字一起使用,因为像 "Friday" 这样的字符串并不准确。 Python docs说:

For time objects, the format codes for year, month, and day should not be used, as time objects have no such values. If they’re used anyway, 1900 is substituted for the year, and 1 for the month and day.

因此,看起来使用不精确的值(例如“Friday”)使用与默认为1相同的后备。

关于python - 奇怪的时间戳转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35611390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com