从Python中的epoch(unix time)开始,如何将datetime对象转换为毫秒?

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

我有一个python datetime对象,我想将其转换为unix时间,或1970年以来的秒/毫秒。

我该怎么做?


我觉得最简单的方法是

1
2
3
4
5
6
import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0


在python 3.3中,添加新方法。

1
datetime.timestamp()

https://docs.python.org/3.3/library/datetime.html datetime.datetime.timestamp


1
2
3
4
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000

或时间模块的帮助(不带日期格式):

1
2
3
4
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0

在http://pleac.sourceforge.net/pleac_python/datesandtimes.html的帮助下回答

文档:

  • time.mktime
  • 江户十一〔一〕号


针对time模块的python 2.7文档的建议

Converting between time representations


你可以用德洛伦在太空和时间旅行!

1
2
3
4
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch

http://delorean.readthedocs.org/en/latest/quickstart.htmlnbsp;


我就是这样做的:

1
2
3
4
5
6
7
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


1
2
3
4
5
6
7
8
9
10
11
12
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))


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> 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

[2]http://docs.python.org/2/library/time.html网站


下面是另一种形式的解决方案,它对时间对象进行了规范化:

1
2
3
4
5
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

这是我根据上面的答案做的一个函数

1
2
3
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

您可以这样包装返回值:str(int(res))返回它时不带十进制值,用作字符串或只返回int(不带str)


1
2
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000


熊猫代码:

1
2
3
4
import pandas

def to_millis(dt):
    return int(pandas.to_datetime(dt).value / 1000000)


将日期时间转换为unixtimestampmillis的另一个解决方案。

1
2
3
4
5
6
7
8
9
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;
    }