将日期字符串解析为 UTC UNIX 格式
Parse Date String to UTC UNIX Format
我有一个字符串格式的时间戳
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?
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
得到的值相匹配
我有一个字符串格式的时间戳
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?
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