Houman
Houman

Reputation: 66320

How to convert a UTC datetime string into date?

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.

Upvotes: 0

Views: 798

Answers (2)

aneroid
aneroid

Reputation: 15962

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.

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54203

import dateutil.parser

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

If you don't have dateutil, get it.

pip install python-dateutil

Upvotes: 2

Related Questions