如何从 Python 2.7 中带时区的日期时间字符串获取 UNIX 时间
How to get the UNIX time from datetime string with timezone in Python 2.7
我想从日期时间字符串中获取 UNIX 时间戳,例如“2021-11-20T12:42:00-08:00”。
我用谷歌搜索了解决方案,但没有找到答案。
使用 python-dateutil 这很简单
from dateutil.parser import parse
dt = parse('2021-11-20T12:42:00-08:00')
timestamp = dt.timestamp()
# in py2.7 you cannot use .timestamp so the following should work
import pytz
timestamp = time.mktime(dt.astimezone(pytz.utc).timetuple())
我想从日期时间字符串中获取 UNIX 时间戳,例如“2021-11-20T12:42:00-08:00”。 我用谷歌搜索了解决方案,但没有找到答案。
使用 python-dateutil 这很简单
from dateutil.parser import parse
dt = parse('2021-11-20T12:42:00-08:00')
timestamp = dt.timestamp()
# in py2.7 you cannot use .timestamp so the following should work
import pytz
timestamp = time.mktime(dt.astimezone(pytz.utc).timetuple())