我有一个Python datetime对象,我想将其转换为unix时间,或自1970 epoch以来的秒/毫秒。
我怎么做呢?
我有一个Python datetime对象,我想将其转换为unix时间,或自1970 epoch以来的秒/毫秒。
我怎么做呢?
当前回答
这是将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;
}
其他回答
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))
下面是一个基于上面答案的函数
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
你可以像这样包装返回值: 返回不带十进制值的字符串或只是int(不带str)
Python 2.7文档对time模块的建议
一段熊猫代码:
import pandas
def to_millis(dt):
return int(pandas.to_datetime(dt).value / 1000000)
你可以用德罗宁去时空旅行!
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch
http://delorean.readthedocs.org/en/latest/quickstart.html