tags:

views:

600

answers:

3

Hi, how to convert python date format to 10 digit date format for mysql

example: date in python -> 11-05-09

to something like 1239992972 (10 digit)

Thanks

+4  A: 

You can use the time module's strptime - you pass in a string time (e.g. 11-05-09) and a format and it will return a struct_time, which you can get the numerical value from (by calling time.mktime on the returned struct_time). See http://docs.python.org/library/time.html#time.strptime for further details.

HarryM
+2  A: 

If it is a datetime obj, you can do:

import time
time.mktime(datetime_obj.timetuple())

If not:

time.mktime(time.strptime("11-05-09", "%d-%m-%y"))
Nadia Alramli
A: 

Use time.strptime() to convert the date into a time tuple, and then time.mktime() (or calendar.timegm()) to convert that into a floating point time. You'll probably need to truncate it to an integer after.

tm = time.strptime('11-05-09', '%d-%m-%y')
time = time.mktime(tm)
time_int = int(time)

http://docs.python.org/library/time.html

Rodrigo Queiro
your format and date string are swapped, and there's no %f identifier
SilentGhost
You're right - thanks!
Rodrigo Queiro