[Answered ]-Python datetime issue while saving in database

2👍

Many DBs accept datetime.datetime objects.

import datetime

Date1 = '2012-04-24T12:58:52Z'
dt1 = datetime.datetime.strptime(Date1, '%Y-%m-%dT%H:%M:%SZ')
# dt1: datetime.datetime(2012, 4, 24, 12, 58, 52)

and now try to insert dt1 into DB as an object.

👤eumiro

0👍

Use this format for date1 and date2:

date1 = datetime.datetime.strftime(y,"%Y-%m-%dT%H:%M:%S")
date2 = datetime.datetime.strftime(date2,"%Y-%m-%dT%H:%M:%S")

this will result in:

2012-04-24T12:58:52
2012-04-24T12:56:21

the error message you report clearly states that you need this format.

👤snies

0👍

I would store the times as plain integers, in seconds since epoch (UNIX timestamp). This way, you can store it into any database without hassle. The %s format specifier for strftime returns the UNIX timestamp as string—so something along the lines of

int(datetime.datetime.now().strftime('%s'))

should work. You can then convert the timestamp back to a datetime object using datetime.datetime.fromtimestamp(…).

👤igor

0👍

I’m not exactly sure which object you’re trying to store in the DB. As eumiro suggests, many libraries let you store the datetime object directly. But assuming you need to store it as a string, but why can’t you just format the datetime object as the database error suggests (YYYY-MM-DD HH:MM:ss)?

So … like this:

 import datetime

 Date1 = '2012-04-24T12:58:52Z'
 d1 = datetime.datetime.strptime(Date1,"%Y-%m-%dT%H:%M:%SZ")
 d1.strftime("%Y-%m-%d %H:%M:%S") # Store this!

 Date2 = 'Tue, 24 Apr 2012 12:56:21 -0700'
 k = Date2.split(" ")
 y = " ".join(k[1:len(k)-1])
 d2 = datetime.datetime.strptime(y,"%d %b %Y %H:%M:%S")
 d2.strftime("%Y-%m-%d %H:%M:%S") # Store this!

This may be outside the scope of your question, but note that with Date2, you’re stripping out the timezone information (-0700). If that’s important to you, you should parse and store that somehow. There’s a %z option in strptime that parses this, but it doesn’t seem to work on all platforms unfortunately.

Leave a comment