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?

5
  • That's a Python 3 code. With python 2.x not supported in near future, you should consider using 3.x version. Commented Apr 27, 2019 at 5: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? Commented Apr 27, 2019 at 5:25
  • You can: 1. Ignore timezone while parsing with slicing, 2. Use dateutil, or 3. Migrate to Python 3. Commented Apr 27, 2019 at 5:35
  • @Austin, can you able to guide me on dateutil? Commented Apr 27, 2019 at 5:39
  • 1
    This would help: stackoverflow.com/a/12282040/8472377 Commented Apr 27, 2019 at 5:46

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.