简体   繁体   中英

Converting date to datetime object python

I have a date which I convert into iso format using:

#createDate is fetched from a json output of an API  
createDate = device['createDate']

# Convert into iso format
# Sample output value : 2014-11-13T16:23:19+00:00
create_date_utcFormat = dateparser.parse(createDate).astimezone(tz.tzutc()).isoformat()

When I try adding this object to DB I get SQLite DateTime type only accepts Python datetime and date objects as input. How can I convert create_date_utcFormat into datetime object?

I'm going to give you a more generic answer to these kinds of problems. If you are having trouble matching types, two things can really help:

  1. Interactive Debugging
  2. type()

Commit the following to memory:

import pdb; pdb.set_trace()

Putting this line anywhere in your code will pause execution of your script when it reaches that point and drop you to a (pdb) prompt, which is similar to the regular python shell, except you can only do one line at a time and there are a few commands available ( c for continue probably being the most important to know).

From here you can use type() to determine what type objects and variables are, and hopefully discover what Daniel said in his answer--that type(dateparser.parse(createDate).astimezone(tz.tzutc())) is already a datetime object.

You had a datetime, but you converted it back to a string with .isoformat() . Don't do that.

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