0

There is a datetime string that I would like to convert back into a date. The time zone is giving me trouble and I don't know how to solve it.

datetime.datetime.strptime(json_event['date_time'], '%a, %d %b %Y %H:%M:%S %Z')

I get the error message:

ValueError: time data 'Tue, 08 Apr 2014 17:57:34 -0000' does not match format '%a, %d %b %Y %H:%M:%S %Z'

If I leave %Z out, I get this error message:

ValueError: unconverted data remains: -0000

The date is originally a UTC:

current_date = datetime.datetime.utcnow()

UPDATE:

I would like to solve this natively without any external libraries such as dateutil.parser, hence the solution in the duplicate doesn't help me.

Houman
  • 64,245
  • 87
  • 278
  • 460
  • possible duplicate of [How do I parse timezones with UTC offsets in Python?](http://stackoverflow.com/questions/1302161/how-do-i-parse-timezones-with-utc-offsets-in-python) – anon582847382 Apr 08 '14 at 18:10
  • I don't want to use `dateutil.parser`. Is there anyway to deal with this natively? – Houman Apr 08 '14 at 18:21
  • there are two other good answers on that question, check them out – anon582847382 Apr 08 '14 at 18:24
  • You mean the accepted answer there is a good solution? Read the comment below it. I leave this here, maybe someone else has a better idea. Thanks – Houman Apr 08 '14 at 18:29

2 Answers2

2
import dateutil.parser

date = dateutil.parser.parse(json_event['date_time'])

If you don't have dateutil, get it.

pip install python-dateutil
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • Sorry, I am aware of this solution. I rather not use any external libs, if possible. – Houman Apr 08 '14 at 18:23
  • 1
    @Hooman then you'll have to do some string manipulation, since the python stdlib doesn't handle `-0000` (and etc) – Adam Smith Apr 08 '14 at 18:25
0

If you are always getting UTC times: Ignore the last 6 chars (space, sign, 4 digts) and then convert to datetime as you've done without the %Z.

One issue you'll have is that your system will assume that it is your local timezone and if you convert it to any other timezone, it will convert wrongly. In that case, next step is to use this answer from another question.

If you get non-UTC times as well:

  1. crop out the last 6 chars.
  2. Do the strptime on the last 4 digits, with the format HHMM (%H%M) --> Y
  3. Get the sign and reverse in step 5 below.
  4. Then get the rest of the datetime as you have above (leaving those last 6 chars and no %Z in the format) --> X
  5. Then X-Y (or X+Y, invert what is got from step 3) will give you a datetime object. Then follow the steps in the linked answer to make the datetime obj timezone aware.
Community
  • 1
  • 1
aneroid
  • 12,983
  • 3
  • 36
  • 66