格式化时间戳到日期给出错误的结果
Formatting a timestamp to date giving wrong result
我正在尝试将时间戳 1584474718199
格式化为日期,但它给了我错误的日期。这就是我现在得到的 2020-03-18
,而正确的日期应该是 2020-03-17
。我怎样才能做到这一点?
我目前的做法:
from datetime import datetime
timestamp = 1584474718199/1000
dt_object = datetime.fromtimestamp(timestamp)
print(f"{dt_object:%Y-%m-%d}")
在我的电脑上(位于 PST)你的代码 returns:
2020-03-17
打印时分秒:
timestamp = datetime.fromtimestamp(timestamp)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
Returns:
2020-03-17 12:51:58
可能是您当地的时区导致了问题,在这种情况下,您可以尝试将其本地化为 UTC:
from datetime import datetime
import pytz
dt_object = datetime.utcfromtimestamp(timestamp)
print(f"{dt_object:%Y-%m-%d %H:%M:%S}")
哪个returns:
2020-03-17 19:51:58
您可能还想检查本地 UTC 偏移量:
utc_offset = datetime.fromtimestamp(timestamp) - datetime.utcfromtimestamp(timestamp)
utc_offset_hours = utc_offset.seconds/(60*60) + utc_offset.days*24
print(f"{utc_offset_hours} hours")
我正在尝试将时间戳 1584474718199
格式化为日期,但它给了我错误的日期。这就是我现在得到的 2020-03-18
,而正确的日期应该是 2020-03-17
。我怎样才能做到这一点?
我目前的做法:
from datetime import datetime
timestamp = 1584474718199/1000
dt_object = datetime.fromtimestamp(timestamp)
print(f"{dt_object:%Y-%m-%d}")
在我的电脑上(位于 PST)你的代码 returns:
2020-03-17
打印时分秒:
timestamp = datetime.fromtimestamp(timestamp)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
Returns:
2020-03-17 12:51:58
可能是您当地的时区导致了问题,在这种情况下,您可以尝试将其本地化为 UTC:
from datetime import datetime
import pytz
dt_object = datetime.utcfromtimestamp(timestamp)
print(f"{dt_object:%Y-%m-%d %H:%M:%S}")
哪个returns:
2020-03-17 19:51:58
您可能还想检查本地 UTC 偏移量:
utc_offset = datetime.fromtimestamp(timestamp) - datetime.utcfromtimestamp(timestamp)
utc_offset_hours = utc_offset.seconds/(60*60) + utc_offset.days*24
print(f"{utc_offset_hours} hours")