我有两个变量:一个是纪元时间,另一个是正常日期时间,
df['epochtime']
0 1457586382
1 1457586382
2 1457586391
3 1457586692
4 1457586391
5 1457586391
6 1457586692
7 1457586692
8 1457572611
df['time']
0 2016-03-10 00:06:21.903
1 2016-03-10 00:06:21.908
2 2016-03-10 00:06:30.895
3 2016-03-10 00:06:30.895
4 2016-03-10 00:06:30.899
5 2016-03-10 00:06:30.899
6 2016-03-10 00:06:31.045
7 2016-03-10 00:06:31.094
8 2016-03-10 01:16:51.390
我想要这两个时间之间的差异(以秒为单位)。以下是我的尝试,
pd.to_datetime(df['epochtime'], unit ='s' ) - df['time']
以下是我的输出,
0 00:00:00.097000
1 00:00:00.092000
2 00:00:00.105000
3 00:05:01.105000
4 00:00:00.101000
5 00:00:00.101000
6 00:05:00.955000
7 00:05:00.906000
8 -1 days +23:59:59.610000
我想以秒为单位将其设置为整数。同样对于第 8 个值,由于某种奇怪的原因,差异为 -1 天,它应该只是秒。谁能帮我把秒差作为整数?
您必须将日期时间转换为纪元时间,然后进行算术减法。
正如您所说,您始终使用 UTC 时间,您需要使用 calendar.timegm()
,因为它需要 UTC 时间作为参数。
import time
import datetime
import calendar
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
def local_datetime_2_timestamp(local_datetime):
'''strptime takes local datetime as parameter'''
timestamp = str(time.mktime(datetime.datetime.
strptime(local_datetime, TIME_FORMAT).timetuple()))[:-2]
return timestamp
def utc_2_timestamp(utc_datetime):
'''timegm takes UTC time as parameter'''
return calendar.timegm(utc_datetime.timetuple())
print local_datetime_2_timestamp("2016-03-10 00:06:21.903".split(".")[0])
print utc_2_timestamp(datetime.datetime(2016,3,10,0,6,21))
from time import mktime, strptime
date_a = '20-01-2015 11:05:02'
epoch_b = 1457586692
epoch_a = int(mktime(strptime(date_a, '%d-%m-%Y %H:%M:%S')))
print(epoch_a - epoch_b)