Search code examples
pythonstringdatetimestrptime

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!


Solution

  • %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