0

Follow up to: Convert a list of sample dates into GMT?

I have some date samples: Like:

Mon, 21 Nov 94 04:28:18 CST 
dec 21 94 17:05 BST

I want to convert this into GMT. For first example it should print:

1994-11-21 10:28:18 

Right now it is printing:

1994-11-21 04:28:18

I tried this:

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
Community
  • 1
  • 1
blackmamba
  • 1,952
  • 11
  • 34
  • 59
  • possible duplicate of [Converting string into datetime](http://stackoverflow.com/questions/466345/converting-string-into-datetime) – oz123 Jan 06 '14 at 20:51
  • But that doesn't have timezone. Here output depends on the timezone. – blackmamba Jan 06 '14 at 20:53
  • If the time zone is always at the end couldn't you use slice notation to get the last three chars and use that? – kylieCatt Jan 06 '14 at 21:00
  • I was thinking the same but how to go about it? – blackmamba Jan 06 '14 at 21:03
  • So, do you feel your [previous question](http://stackoverflow.com/questions/20956568/convert-a-list-of-sample-dates-into-gmt) [answered](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work), and expect followups proposed for that one? :) – alko Jan 06 '14 at 21:26
  • @wannaC do you have different timezones, or CST and BST are the only ones? – alko Jan 06 '14 at 21:32
  • I have different timezones. – blackmamba Jan 07 '14 at 05:02

2 Answers2

0

As written (with proper indentation in the for loop of course), your script worked for me using python 2.6.6, pytz 2013.9 and python-dateutil-1.5. The output:

$ 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
  • BST is UTC +1, so not completely as expected. Though I can't reproduce CST recognision. – alko Jan 06 '14 at 21:34
0

If you have a fixed amount of timezones to recognize, you can provide info about them to 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
alko
  • 46,136
  • 12
  • 94
  • 102
  • Works perfectly. But I have other time zones. It would do even if it's just all American and Europe timezones – blackmamba Jan 07 '14 at 05:48