Scott
Scott

Reputation: 705

Python Datetime object

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!

Upvotes: 2

Views: 324

Answers (2)

Kevin
Kevin

Reputation: 76254

%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

Upvotes: 4

NanoPish
NanoPish

Reputation: 1521

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.

Upvotes: 2

Related Questions