我有一个Python datetime对象,我想将其转换为unix时间,或自1970 epoch以来的秒/毫秒。
我怎么做呢?
我有一个Python datetime对象,我想将其转换为unix时间,或自1970 epoch以来的秒/毫秒。
我怎么做呢?
当前回答
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000
其他回答
在我看来,最简单的方法是
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
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))
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000
这是将datetime转换为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;
}
很多答案在python2中不起作用,或者没有从datetime中保存毫秒。这对我很有用
def datetime_to_ms_epoch(dt):
microseconds = time.mktime(dt.timetuple()) * 1000000 + dt.microsecond
return int(round(microseconds / float(1000)))