简体   繁体   中英

python convert string to datetime which is django time format

time = "2019-02-20T04:35:48.679000+00:00"

>>> import datetime
>>> 
>>> date_time_str = "2019-02-20T04:35:48.679000+00:00"
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime
    (data_string, format))
ValueError: time data '2019-02-20T04:35:48.679000+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f'

The time is Django format time. Unfortunately i am storing the same in an CharField() so it is giving time as a string while fetching data from database.

How can i convert it into actual time.

You need to account for the 'T', and I don't know how to match the "+00:00" part unless it's simply a literal that's always that value. So this works:

import datetime
date_time_str = "2019-02-20T04:35:48.679000+00:00"
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%dT%H:%M:%S.%f+00:00')

try to use python-dateutil

install it pip install python-dateutil

and then

from dateutil import parser
dt = parser.parse("2019-02-20T04:35:48.679000+00:00")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM