如何将带时区的字符串转换为unix时间戳python? [英] How to convert a string with timezone to unix timestamp python?

查看:66
本文介绍了如何将带时区的字符串转换为unix时间戳python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据库中获取的日期时间字符串,我想将其转换为 unix 时间戳.

I have a datetime string I get from a database and I want to convert it to unix timestamp.

我不确定这样做的方法是什么.

I am not sure what is the way to do it.

db_timestamp = '2020-08-05 12:48:50+02:00'
f = '%Y-%m-%d %H:%M:%S%z'
timestamp = datetime.strptime(db_timestamp , f)

TypeError: strptime() argument 1 must be str, not datetime.datetime 

我尝试的另一种方法如下

Another way I tried was as following

python_timestamp = datetime.isoformat(db_timestamp)
test_timestamp = datetime.strptime(python_timestamp , f)

然后我得到以下错误

ValueError: time data '2020-08-05T12:48:50+02:00' does not match format '%Y-%m-%d %H:%M:%S%z'

如何修复这个错误?db_timestamp 的正确字符串格式应该是什么?

How to fix this error? What should be the correct string format for db_timestamp?

推荐答案

假设您运行 Python 3.7 或更高版本,您需要的是 fromisoformat 来解析字符串和 timestamp() 获取自纪元 UNIX 时间 (POSIX) 以来的秒数.

assuming you run Python 3.7 or higher, what you want is fromisoformat to parse the string and timestamp() to get seconds since the epoch UNIX time (POSIX).

from datetime import datetime
db_timestamp = '2020-08-05 12:48:50+02:00'
# to datetime object:
dt = datetime.fromisoformat(db_timestamp)
# to UNIX time:
ts = dt.timestamp()
print(repr(dt), ts)
>>> datetime.datetime(2020, 8, 5, 12, 48, 50, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200))) 1596624530.0

这篇关于如何将带时区的字符串转换为unix时间戳python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆