1

I want to write a code in python which converts all of the dates(in various formats) to a standard format. I saw a question on stackoverflow Converting various different date formats in to one common date format Java or Perl?

I want to do it in python.

I tried this:

DEFAULT_DATE = datetime.datetime(datetime.datetime.now().year, 1, 1)
dt = parser.parse(date,default = DEFAULT_DATE)

 Original                                                       Modified
 1.1995-01-24T09:08:17.1823213                           1995-01-24 09:08:17.182321
 2. Wed, 16 Jun 94 07:29:35 CST                          1994-06-16 07:29:35
 3. Thu, 13 Oct 94 10:13:13 -0700                        1994-10-13 10:13:13-07:00
 4. Wed, 9 Nov 1994 09:50:32 -0500 (EST)                 1994-11-09 09:50:32-05:00
 5. 21 dec 17:05                                         2014-12-21 17:05:00
 6. 21-dec 17:05                                         2014-12-21 17:05:00
 7. 21/dec 17:05                                         2014-12-21 17:05:00
 8. 21/dec/93 17:05                                      1993-12-21 17:05:00
 9. 16 Nov 94 22:28:20 PST                               1994-11-16 22:28:20
 10. 1999 10:02:18 'GMT'                                 1999-01-01 10:02:18+00:00

I need to convert time to GMT as well. Like for 2,3,4,9 it displays the same time as given in original list. I want to convert them to GMT. For dates and times like in 4,9 it's in EST and PST etc., I want to convert them into GMT.

Community
  • 1
  • 1
blackmamba
  • 1,952
  • 11
  • 34
  • 59

2 Answers2

1

You can convert all the datetimes to UTC, treating all naive datetime objects as UTC:

import pytz
def to_utc(dt):
    try:
        return dt.astimezone(pytz.utc)
    except ValueError:
        return pytz.utc.localize(dt)

Demo:

>>> print '\n'.join(original)
1995-01-24T09:08:17.1823213
Wed, 16 Jun 94 07:29:35 CST
Thu, 13 Oct 94 10:13:13 -0700
Wed, 9 Nov 1994 09:50:32 -0500 (EST)
21 dec 17:05
21-dec 17:05
21/dec 17:05
21/dec/93 17:05
16 Nov 94 22:28:20 PST
1999 10:02:18 'GMT'
>>> modified = [parser.parse(od, default=DEFAULT_DATE) for od in original]
>>> in_utc = [to_utc(md) for md in modified]
>>> for d in in_utc:
...     print d
...
1995-01-24 09:08:17.182321+00:00
1994-06-16 07:29:35+00:00
1994-10-13 17:13:13+00:00
1994-11-09 14:50:32+00:00
2014-12-21 17:05:00+00:00
2014-12-21 17:05:00+00:00
2014-12-21 17:05:00+00:00
1993-12-21 17:05:00+00:00
1994-11-16 22:28:20+00:00
1999-01-01 10:02:18+00:00
alko
  • 46,136
  • 12
  • 94
  • 102
  • If I am converting Wed, 16 Jun 94 07:29:35 CST to GMT that means time should be 1994-06-16 13:29:35+00:00, right? – blackmamba Jan 06 '14 at 19:23
0

Here, checkout the docs for dateutil.parser, especially the section on tzinfo may be of use to you.

misakm
  • 122
  • 6