跟进:Convert a list of sample dates into GMT?
我有一些日期样本: 喜欢:
Mon, 21 Nov 94 04:28:18 CST
dec 21 94 17:05 BST
我想将其转换为GMT。对于第一个例子,它应该打印:
1994-11-21 10:28:18
现在正在打印:
1994-11-21 04:28:18
我试过了:
from dateutil import parser
import pytz
import datetime
def to_utc(dt):
try:
return dt.astimezone(pytz.utc)
except ValueError:
return pytz.utc.localize(dt)
DEFAULT_DATE = datetime.datetime(datetime.datetime.now().year, 1, 1)
file = open("date_time.txt",'rb')
for line in file:
date = line.rstrip('\n')
print date
dt = parser.parse(date, default=DEFAULT_DATE)
in_utc = to_utc(dt)
print in_utc
答案 0 :(得分:0)
正如所写(当然在 for 循环中有适当的缩进),你的脚本使用python 2.6.6,pytz 2013.9和python-dateutil-1.5为我工作。输出:
$ python dt.py Mon, 21 Nov 94 04:28:18 CST 1994-11-21 10:28:18+00:00 dec 21 94 17:05 BST 1994-12-21 17:05:00+00:00
答案 1 :(得分:0)
如果您要识别固定数量的时区,可以向dateutil.parser
提供有关这些时区的信息:
>>> tz = {'CST':-6*3600, 'BST':+1*3600}
>>> for line in """Mon, 21 Nov 94 04:28:18 CST
... dec 21 94 17:05 BST""".splitlines():
... date = line.rstrip('\n')
... print date
... dt = parser.parse(date, default=DEFAULT_DATE, tzinfos=tz)
... in_utc = to_utc(dt)
... print in_utc
...
Mon, 21 Nov 94 04:28:18 CST
1994-11-21 10:28:18+00:00
dec 21 94 17:05 BST
1994-12-21 16:05:00+00:00