datetime.utcfromTimestamp 在 Python 中更改时间

datetime.utcfromtimestamp changing time in python

提问人:David Masip 提问时间:9/14/2023 最后编辑:FObersteinerDavid Masip 更新时间:9/14/2023 访问量:56

问:

我有一个表示日期时间(ts)的字符串。我想将其转换为int,然后用于恢复相同的日期时间:datetime.utcfromtimestamp

ts = '2023-07-10 14:06:22.000 UTC'
int_ts = int(datetime.strptime(ts, "%Y-%m-%d %H:%M:%S.%f %Z").timestamp() * 1000) # change this line, cannot change the previous or next
back_to_ts = datetime.utcfromtimestamp(int_ts / 1000)
print(f"{back_to_ts = }, {ts = }, {int_ts = }")

但是,我得到以下输出:

back_to_ts = datetime.datetime(2023, 7, 10, 12, 6, 22), ts = '2023-07-10 14:06:22.000 UTC', int_ts = 1688990782000

我只能更改第二行,我应该如何更改它才能获得以下输出?

back_to_ts = datetime.datetime(2023, 7, 10, 14, 6, 22), ts = '2023-07-10 14:06:22.000 UTC', int_ts = 1688990782000
Python 日期时 UTC

评论

0赞 FObersteiner 9/14/2023
%Z这里可能具有误导性;它基本上使解析器忽略了输入指定 UTC 的事实。生成的 datetime 对象将是幼稚的,未设置时区。关于考虑这一点。与 tz 参数集一起使用可能是更好的选择。utcfromtimestampfromtimestamp

答:

2赞 kevin41 9/14/2023 #1

在将 datetime 对象转换为时间戳之前,您需要替换 datetime 对象中的时区。请参阅第二行的部分。.replace(tzinfo=timezone.utc)

ts = '2023-07-10 14:06:22.000 UTC'
int_ts = int(datetime.strptime(ts, "%Y-%m-%d %H:%M:%S.%f %Z").replace(tzinfo=timezone.utc).timestamp() * 1000)
back_to_ts = datetime.utcfromtimestamp(int_ts / 1000)

输出:

back_to_ts = datetime.datetime(2023, 7, 10, 14, 6, 22), ts = '2023-07-10 14:06:22.000 UTC', int_ts = 1688997982000

评论

1赞 FObersteiner 9/14/2023
替换 tzinfo 的替代方法是修改输入字符串:datetime.fromisoformat(ts.replace(" UTC", "+00:00"))
0赞 David Masip 9/14/2023
忘了添加时区是从 datetime 导入的,但是是的,它可以工作
0赞 Anis Rafid 9/14/2023 #2

您可以使用 pytz 库来解析输入日期时间字符串以正确处理 UTC 时区。只需要更改第二行。以下是修改后的代码:

import pytz
from datetime import datetime

ts = '2023-07-10 14:06:22.000 UTC'
int_ts = int(pytz.utc.localize(datetime.strptime(ts, "%Y-%m-%d %H:%M:%S.%f %Z")).timestamp() * 1000)
back_to_ts = datetime.utcfromtimestamp(int_ts / 1000)
print(f"{back_to_ts = }, {ts = }, {int_ts = }")

输出:

back_to_ts = datetime.datetime(2023, 7, 10, 14, 6, 22), ts = '2023-07-10 14:06:22.000 UTC', int_ts = 1688990782000