纪元时间和正常日期之间的差异,以秒为单位 - 蟒蛇

时间:2016-03-16 22:38:24

标签: python

我有两个变量:一个是纪元时间,另一个是正常的日期时间,

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天,它应该只是秒。任何人都可以帮助我将秒差作为整数吗?

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:0)

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)