Reputation: 66320
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
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:
%H%M
) --> Y
X
Upvotes: 0
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