0

I have a UTC format date string represented as :

ds = "2019-06-15 17:18:06 UTC"

I am trying to convert it into a python utc datetime object like this :

d = datetime.strptime(ds,'%Y-%m-%dT%H:%M:%SZ')

However I am getting the following error :

ValueError: time data '2019-06-15 17:18:06 UTC' does not match format '%Y-%m-%dT%H:%M:%SZ'

So what is the correct format to pass, so that I get a datetime object in UTC timezone?

2 Answers 2

1

Use format %Y-%m-%d %H:%M:%S %Z

Ex:

import datetime
import pytz

ds = "2019-06-15 17:18:06 UTC"
nDate = datetime.datetime.strptime(ds,'%Y-%m-%d %H:%M:%S %Z') 
timezone = pytz.timezone(ds.split()[-1])
d_aware = timezone.localize(nDate)
print(d_aware)
print(d_aware.tzinfo) 

Output:

2019-06-15 17:18:06+00:00
UTC
Sign up to request clarification or add additional context in comments.

Comments

0

The format string you are currently using doesn't match with the datetime string format which you provided. That's why its throwing error.

 datetime.strptime(ds,'%Y-%m-%d %H:%M:%S UTC')

1 Comment

Using this format string, the resulting object is not timezone aware. Of course if you know your input is UTC, this can be handled manually, but is there a way to automatically parse the UTC marker? Notice that using d.strftime('%Y-%m-%d %H:%M:%S %Z') on a timezone aware object will generate the UTC marker, and datetime.strptime(ds,'%Y-%m-%d %H:%M:%S %Z') will consume it, but the resulting object is not timezone aware.

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.