pythondatetimetimestampstrptime

Python: Parse timestamp string with 7 digits for microseconds to datetime


I have a timestamp string that looks like this:

2019-02-16T10:41:20.6080000+01:00

I have to parse it to datetime. Because there are 7 instead of 6 digits for microseconds the following format does not match:

timestamp = "2019-03-14T14:37:37.000000+01:00"
parsed_timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f%z") #ValueError: time data '2019-03-14T14:37:37.0000000+01:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

How can I parse this format?


Solution

  • Using dparser:

    import dateutil.parser as dparser
    dt_1 = '2019-02-16T10:41:20.6080000+01:00'
    print("Datetime: {}".format(dparser.parse(dt_1,fuzzy=True)))
    

    OUTPUT:

    Datetime: 2019-02-16 10:41:20.608000+01:00
    

    If you want the date component:

    print("Date: {}".format(dparser.parse(dt_1,fuzzy=True).date()))
    

    OUTPUT:

    Date: 2019-02-16