在python 3的Pytz模块中将EST,CST和DST时区转换为Unix时间戳 [英] Convert EST, CST and DST timezones to unix timestamp in Pytz Module in Python 3

查看:55
本文介绍了在python 3的Pytz模块中将EST,CST和DST时区转换为Unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下格式的日期:

I have a date that comes in the following format:

2019-12-13 20:18 EST 2019-12-13 20:18 DST 2019-12-13 20:18 CST

我想将它们转换为 unix时间戳 .

I would like to convert them to unix timestamp.

我正在使用 Pytz 模块.

到目前为止,我已经尝试通过以下方式使用 datetime 模块:

So far, I have tried using datetime module in the following way:

time_est = '2019-12-13 20:18 EST'

datetime.datetime.strptime(time_est, '%Y-%m-%d %H:%M %z')

这似乎也不起作用.任何建议或技巧将不胜感激.

This does not seem to work either. Any suggestions out there or tips would be appreciated.

推荐答案

在许多情况下,时区名称缩写不明确(一种表示不同时区的缩写,

Time zone name abbreviations are ambiguous in many cases (one abbreviation for different time zones, see e.g. here), so it is best to explicitly define what your abbreviations mean. You can do so by supplying a mapping dict to dateutil's parser.

import dateutil

tzmapping = {'EST': dateutil.tz.gettz('America/New_York'),
             'EDT': dateutil.tz.gettz('America/New_York'),
             'CST': dateutil.tz.gettz('America/Chicago'),
             'CDT': dateutil.tz.gettz('America/Chicago')
             # add more if needed...}

time_eastern = '2019-12-13 20:18 EST'

dtobj = dateutil.parser.parse(time_eastern, tzinfos=tzmapping)
# datetime.datetime(2019, 12, 13, 20, 18, tzinfo=tzfile('US/Eastern'))

time_unix = dtobj.timestamp()
# 1576286280.0

如果必须使用pytz,则必须忽略字符串中的 EST ,解析为原始日期时间,本地化为适当的时区,然后加上时间戳:

If you must use pytz, you'll have to ignore EST in the string, parse to naive datetime, localize to the appropriate time zone and then take the timestamp:

import datetime
import pytz

eastern = pytz.timezone('America/New_York')
dtobj = eastern.localize(datetime.datetime.strptime(time_eastern, '%Y-%m-%d %H:%M EST'))
time_unix = dtobj.timestamp()
# 1576286280.0

这篇关于在python 3的Pytz模块中将EST,CST和DST时区转换为Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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