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

标签 python time timezone unix-timestamp utc

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

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/

相关文章:

mysql - 设置时区mysql

rest - 谷歌日历 API : TimeZone not taken into account by google server?

java - 转换为 JSON 字符串时日期递减一天 - Java

python - py/pandas dataframe - 如何将每日收盘价更改为每月收盘价?

python - 我将如何在基于银行抢劫文本的游戏中实现计时器,时钟上的时间越长,被盗的钱就越多。

python - 获取当前时间之前可被 5 整除的最近时间

linux - Linux下如何查看文件创建时间?

Python Enum 防止无效的属性赋值

python - 如何在条件检查时从现有数据帧复制数据帧中的选定行? [Python]

javascript - 在 JavaScript 中将 "9:00 pm"转换为 "21:00:00"的正确方法是什么?