Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Converting from `datetime.datetime` to `time.time`

In Python, how do I convert a datetime.datetime into the kind of float that I would get from the time.time function?

like image 863
Ram Rachum Avatar asked Nov 05 '11 18:11

Ram Rachum


People also ask

How do I convert datetime to epoch time?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

How do I change the format of a time in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I convert datetime to date?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.


2 Answers

It's not hard to use the time tuple method and still retain the microseconds:

>>> t = datetime.datetime.now() >>> t datetime.datetime(2011, 11, 5, 11, 26, 15, 37496)  >>> time.mktime(t.timetuple()) + t.microsecond / 1E6 1320517575.037496 
like image 171
Raymond Hettinger Avatar answered Sep 21 '22 11:09

Raymond Hettinger


time.mktime(dt_obj.timetuple()) 

Should do the trick.

like image 27
Amber Avatar answered Sep 22 '22 11:09

Amber