2

I am currently having an issue converting an incoming datetime string to a datetime object using Python's built in strptime() method. Here is what I currently have:

def fixDateTimeField(datetimeString):
    # Convert from 2012-08-07T00:00:00Z to 2012-08-07T00:00:00.000Z
    datetime_object = datetime.strptime(datetimeString, "%y-%m-%dT%H:%M:%SZ")
    return datetime_object

Like the comment says, I am trying to convert the string "2012-08-07T00:00:00Z" to a datetime object that looks like 2012-08-07T00:00:00.000Z but I am getting an error in my console that says: "ValueError: time data '2012-08-07T00:00:00Z' does not match format '%y-%m-%dT%H:%M:%SZ'". The format seems correct to me and i'm not seeing the issue.

Thanks in advance!

2
  • datetime.strptime(datetimeString, "%Y-%m-%dT%H:%M:%SZ") Commented Jul 26, 2018 at 13:18
  • could you accept my answer if you think it is correct ? Commented Jul 31, 2018 at 16:03

2 Answers 2

4

%y is for two-digit years. You have a four-digit year.

Try using %Y instead.

>>> from datetime import datetime
>>> datetimeString = "2012-08-07T00:00:00Z"
>>> print(datetime.strptime(datetimeString, "%Y-%m-%dT%H:%M:%SZ"))
2012-08-07 00:00:00
Sign up to request clarification or add additional context in comments.

1 Comment

Ah I knew it was something small. Thanks!
2

A nice way to parse your iso-8601 datetime string "2012-08-07T00:00:00Z" to a datetime object is using dateutil.

import dateutil.parser
yourdate = dateutil.parser.parse(datestring)

With strptime:

datetime.datetime.strptime( "2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")

Works. As an other answer said, the Y must be capitalized for strptime to work with 4 digit years.

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.