Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.

How do I do this?

like image 231
SuperString Avatar asked Aug 09 '11 16:08

SuperString


People also ask

How do you convert datetime to seconds since epoch Python?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.

How do you convert datetime to milliseconds?

Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

How do I convert time to milliseconds Python?

You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time. time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off.


2 Answers

It appears to me that the simplest way to do this is

import datetime  epoch = datetime.datetime.utcfromtimestamp(0)  def unix_time_millis(dt):     return (dt - epoch).total_seconds() * 1000.0 
like image 139
Sophie Alpert Avatar answered Oct 15 '22 09:10

Sophie Alpert


In Python 3.3, added new method timestamp:

import datetime seconds_since_epoch = datetime.datetime.now().timestamp() 

Your question stated that you needed milliseconds, which you can get like this:

milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000 

If you use timestamp on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.

like image 43
eshizhan Avatar answered Oct 15 '22 10:10

eshizhan