0

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?

Mihir Shah
  • 948
  • 10
  • 17
  • That's a Python 3 code. With python 2.x not supported in near future, you should consider using 3.x version. – Austin Apr 27 '19 at 05:20
  • @Austin, you are right but client environment is python 2.x. As per you if I am not wrong, if I wanted to stick with python 2.x then I have to remove UTC OFFSET value from the coming date-time string and then have to convert to date-time, correct? – Mihir Shah Apr 27 '19 at 05:25
  • You can: 1. Ignore timezone while parsing with slicing, 2. Use [dateutil](http://labix.org/python-dateutil), or 3. Migrate to Python 3. – Austin Apr 27 '19 at 05:35
  • @Austin, can you able to guide me on dateutil? – Mihir Shah Apr 27 '19 at 05:39
  • 1
    This would help: https://stackoverflow.com/a/12282040/8472377 – Austin Apr 27 '19 at 05:46

2 Answers2

2

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
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1

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.

Harshil Shah
  • 142
  • 2
  • 3
  • 13