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?
Join Stack Overflow to learn, share knowledge, and build your career.
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
%s
is OS dependent! Thus anyone want the code works reliably regardless on which OS, should NEVER use %s
. For 2.3 < py ver <2.7. One can simply build a total_seconds()
like this: delta.days*86400+delta.seconds+delta.microseconds/1e6
– Wang
Jul 24 '12 at 10:32
dt
must be in UTC (not local). See similar answer with Python 2.6/3 support
– jfs
Oct 28 '12 at 19:50
utcfromtimestamp(0)
may cause a 'tz' offset only if 'tz' is not 0. This is because dt
in dt- epoch
has 'tz' calculated in it where as epoch is UTC time. The best way to calculate epoch is epoch = datetime.datetime(1970, 1, 1)
where timezone is in consideration.
– ahj
Jan 6 '16 at 15:31
datetime.utcfromtimestamp(0)
return a datetime without tzinfo? It's right there in the method name, utcfromtimestamp. In order to make it non-naive I have to do something like datetime.utcfromtimestamp(0).replace(tzinfo=pytz.UTC)
. This is necessary if dt
is timezone aware or else you will get TypeError: can't subtract offset-naive and offset-aware datetimes
– FGreg
Sep 1 '16 at 18:03
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.
.timestamp()
method assumes that a naive input datetime is in the local timezone (and the local time may be ambiguous). If it is in UTC then use dt.replace(tzinfo=timezone.utc).timestamp()
instead.
– jfs
Dec 29 '14 at 1:12
datetime.datetime.timestamp(datetime.datetime.now())
– MarkHu
Feb 1 '18 at 20:01
datetime.datetime.now(pytz.timezone('Europe/Paris')).timestamp() == datetime.datetime.now(pytz.utc).timestamp() == datetime.datetime.utcnow().timestamp()
but not (always) equal to datetime.datetime.now().timestamp()
(this last one is only equal to the rest if the local tz is UTC...)
– Bluu
Jul 12 '18 at 14:28
fromtimestamp
(docs.python.org/3/library/…)
– Flimm
Mar 4 '20 at 14:12
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
.timetuple()
returns tm_isdst=-1
it forces mktime()
to guess. It may guess wrongly during DST (50% chance of an error +/- hour). Both '%s' and mktime()
may use the wrong utc offset for dates from the past. You need a historical timezone db such as provided by pytz
module to reliably convert local time to POSIX timestamp (unless OS already provides such db)
– jfs
May 15 '14 at 19:01
mktime/timetuple
. Also timetuple()
strips fractions of a second and the point of the question is to get the timestamp with millisecond precision.
– jfs
Dec 29 '14 at 1:18
You can use Delorean to travel in space and time!
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch
This is how I do it:
from datetime import datetime
from time import mktime
dt = datetime.now()
sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0
millis_since_epoch = sec_since_epoch * 1000
Recommendedations from the Python 2.7 docs for the time
module
time
module, but the OP asked about datetime
module. FWIW, the simplest current epoch is int(time.time())
– MarkHu
Feb 1 '18 at 19:38
from datetime import datetime
from calendar import timegm
# Note: if you pass in a naive dttm object it's assumed to already be in UTC
def unix_time(dttm=None):
if dttm is None:
dttm = datetime.utcnow()
return timegm(dttm.utctimetuple())
print "Unix time now: %d" % unix_time()
print "Unix timestamp from an existing dttm: %d" % unix_time(datetime(2014, 12, 30, 12, 0))
timegm()
works only with utc time. It doesn't use tm_isdst
therefore you could use utcnow.timetuple()
instead of utcnow.utctimetuple()
. Note: using naive_local_datetime.utctimetuple()
would be wrong here. It doesn't translate local time to utc. Also timetuple()
call strips fractions of a second from the result (whether it matters depends on application). Also the question asks about *milli*seconds, not seconds
– jfs
May 15 '14 at 18:52
utctimetuple()
strips fractions of a second. Multiplying by 1000
won't get them back.
– jfs
Dec 29 '14 at 1:14
>>> import datetime
>>> import time
>>> import calendar
>>> #your datetime object
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 3, 19, 13, 0, 9, 351812)
>>> #use datetime module's timetuple method to get a `time.struct_time` object.[1]
>>> tt = datetime.datetime.timetuple(now)
>>> tt
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=19, tm_hour=13, tm_min=0, tm_sec=9, tm_wday=1, tm_yday=78, tm_isdst=-1)
>>> #If your datetime object is in utc you do this way. [2](see the first table on docs)
>>> sec_epoch_utc = calendar.timegm(tt) * 1000
>>> sec_epoch_utc
1363698009
>>> #If your datetime object is in local timeformat you do this way
>>> sec_epoch_loc = time.mktime(tt) * 1000
>>> sec_epoch_loc
1363678209.0
[1] http://docs.python.org/2/library/datetime.html#datetime.date.timetuple
Here's another form of a solution with normalization of your time object:
def to_unix_time(timestamp):
epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
delta = my_time - epoch
return delta.total_seconds() * 1000.0
A bit of pandas code:
import pandas
def to_millis(dt):
return int(pandas.to_datetime(dt).value / 1000000)
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000
* 1000
, though, you do get seconds_since_epoch
. Upvoting this answer because I don't care about milliseconds right now.
– Michael Scheper
Apr 27 '16 at 21:35
Here is a function I made based on the answer above
def getDateToEpoch(myDateTime):
res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
return res
You can wrap the returned value like this : str(int(res)) To return it without a decimal value to be used as string or just int (without the str)
This other solution for covert datetime to unixtimestampmillis.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}
$ python -c 'import time; print(time.time())'
which gave:1584487455.698623
– MarkHu Mar 17 '20 at 23:27