I received the datetime in below format

timestamp = '2019-03-18 01:50:00 -0800'

and wanted to convert into datetime in python i tried but won't able to pick the UTC offset

from datetime import datetime
from datetime import timedelta
timestamp = '2019-03-18 01:50:00 -0800'
date_format = '%Y-%m-%d %H:%M:%S %z'
d_t =datetime.strptime(timestamp,date_format)

Error i get

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 324, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'

how to pick UTC offset in python 2.7?

2 Answers

1
Harshil Shah On

Install pytz library

sudo easy_install --upgrade pytz

Import pytz to code

from datetime import datetime 
from pytz import timezone 
date_str = "2009-05-05 22:28:15"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") #parse only date & time 
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC')) #get time zone using pytz
print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")

It should help.

1
Devesh Kumar Singh On

Just use dateutil

from dateutil import parser

obj = parser.parse('2019-03-18 01:50:00 -0800')
print(obj)
#2019-03-18 01:50:00-08:00