简体   繁体   English

纪元时间和正常日期之间的差异(以秒为单位)-python

[英]Difference between epoch time and normal date in seconds - python

I have two variables : One is epoch time and other is normal datetime,我有两个变量:一个是纪元时间,另一个是正常的日期时间,

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 

I want the difference between these two times in seconds.我想要这两次之间的差异(以秒为单位)。 The following is my trying,以下是我的尝试,

pd.to_datetime(df['epochtime'], unit ='s' ) - df['time']

The following is my output,以下是我的输出,

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   

I want to make this as integer in seconds.我想以秒为单位将其设为整数。 Also for the 8th value for some strange reason getting difference as -1 days, where it should be seconds only.同样对于第 8 个值,出于某种奇怪的原因,差异为 -1 天,应该仅为秒。 Can anybody help me getting the seconds difference as integer ?有人能帮我把秒差作为整数吗?

You have to convert datetime to epoch time, and then do the arithmetic subtraction.您必须将日期时间转换为纪元时间,然后进行算术减法。

As you said you are always use UTC time, you need to use calendar.timegm() because it takes UTC time as parameter.正如您所说,您总是使用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM