如何将带有时区的字符串转换为Unix时间戳Python?

问题描述

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

我不确定该怎么做。

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 

我尝试的另一种方法是

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的正确字符串格式应该是什么?

解决方法

假设您运行的是Python 3.7或更高版本,那么您需要的是fromisoformat来解析字符串,而timestamp()则是从UNIX时代(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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...