gpt4 book ai didi

python - 将日期字符串解析为 UTC UNIX 格式

转载 作者:行者123 更新时间:2023-12-01 08:40:33 25 4
gpt4 key购买 nike

我有一个字符串格式的时间戳

timestamp_str = '18:02:19 14:14:11 465872'
format_str = '%y:%m:%d %H:%M:%S %f'

为了在 UNIX 中将其转换为 UTC,我编写了以下代码

def str2utc(timestr,formatstr):
timeobj = datetime.datetime.strptime(timestr, formatstr)
time_utc = time.mktime(timeobj.timetuple())
return time_utc

timestamp_utc_unix = str2utc(timestamp_str,format_str)

尽管如此,正如我所知,如果我的系统时间不是 utc,则此方法不起作用。我读过其他帖子,例如

Python strptime() and timezones?

但我就是不知道如何纠正它。我如何更改代码,以便无论我的系统时间是多少,它总是在 unix 中输出 utc?

最佳答案

Python docs :

Note

There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc:

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

or by calculating the timestamp directly:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

所以你的函数看起来像

def str2utc(timestr,formatstr):
timeobj = datetime.datetime.strptime(timestr, formatstr)
time_utc = timeobj.replace(tzinfo=datetime.timezon.utc).timestamp()
return time_utc

我得到的值是 1519049651.465872,它与我从 unixtimestamp.com 得到的值相匹配

关于python - 将日期字符串解析为 UTC UNIX 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53519685/

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