Home > Blockchain >  How to convert a str like this format '2017-12-02 23:55:66.333 01:00' to datetime in pytho
How to convert a str like this format '2017-12-02 23:55:66.333 01:00' to datetime in pytho

Time:01-12

I need to convert a set of strings that is in this format "2017-12-02 23:55:66.333 01:00" to datetime.

I tried using this:

from datetime import datetime

date_time_str = '2017-12-02 23:55:66.333 01:00'

date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S%z')

print ("The date is", date_time_obj)

But i have this output:

>> ValueError: raise ValueError("time data %r does not match format %r" %
ValueError: time data '2017-12-02 23:55:66.333 01:00' does not match format '%Y-%m-%d %H:%M:%S%z'

How can i convert this date or this date_time_str is not valid?

CodePudding user response:

There are two problems:

  • your seconds are greater than 60
  • you need to include the microseconds formatter

Thus to fix it,

from datetime import datetime
date_time_str = '2017-12-02 23:55:06.333 01:00'
date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f%z')
print("The date is", date_time_obj)

yields

The date is 2017-12-02 23:55:06.333000 01:00

You can catch the error caused by the seconds being too large and raise a helpful error message by

from datetime import datetime
date_time_str = '2017-12-02 23:55:06.333 01:00'
try:
    date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f%z')
except ValueError as ve:
    if "unconverted data remains" in ve.args[0]:
        raise ValueError("One of the values in the time string isn't meaninful")
    else:
        raise ve
print("The date is", date_time_obj)

CodePudding user response:

here is what you want to do, missing stripping micorosecond and timezone section :

date_time_str = '2017-12-02 23:55:59.333 01:00'
date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f%z')
print ("The date is", date_time_obj)

output :

The date is 2017-12-02 23:55:59.333000 01:00

or simply using this in python 3.7 :

datetime.fromisoformat(date_time_str)
  •  Tags:  
  • Related