我有一个Python datetime对象,我想将其转换为unix时间,或自1970 epoch以来的秒/毫秒。
我怎么做呢?
我有一个Python datetime对象,我想将其转换为unix时间,或自1970 epoch以来的秒/毫秒。
我怎么做呢?
当前回答
这是另一种形式的解决方案与规范化的时间对象:
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
其他回答
下面是一个基于上面答案的函数
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)
这是将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)))
在Python 3.3中,添加了新的方法timestamp:
import datetime
seconds_since_epoch = datetime.datetime.now().timestamp()
你的问题说你需要毫秒,你可以得到这样的毫秒:
milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000
如果在naive datetime对象上使用时间戳,则假定该对象位于本地时区。如果您不希望发生这种情况,请使用时区感知的datetime对象。
一段熊猫代码:
import pandas
def to_millis(dt):
return int(pandas.to_datetime(dt).value / 1000000)