簡體   English   中英

如何在Python中將時間列表轉換為Unix紀元時間?

[英]How do I convert a list of times into Unix epoch time in Python?

我目前正在使用它來獲取延遲:

def time_deltas(infile): 
entries = (line.split() for line in open(INFILE, "r")) 
ts = {}  
for e in entries: 
    if " ".join(e[2:5]) == "TMsg out: [O]": 
        ts [e[8]] = e[0]  
    elif " ".join(e[2:5]) == "TMsg in: [A]":    
        in_ts, ref_id = e[0], e[7] 
        out_ts = ts.pop(ref_id, None) 
        yield (float(out_ts),ref_id[1:-1],(float(in_ts)*1000 - float(out_ts)*1000))


INFILE = 'C:/Users/klee/Documents/test.txt'
print list (time_deltas(INFILE))

我想將float(out_ts)轉換為Unix紀元秒。

我嘗試了以下方法,但失敗了:

int(time.mktime(time.strptime('(out_ts)', '%H%M%S.%f'))) - time.timezone

 t = time.strptime(float(out_ts), "%H%M%S.%f")
        print "Epoch Seconds:", time.mktime(t.timetuple())

d = datetime.strptime("out_ts", "%H%M%S.%f")
        time.mktime(d.timetuple())

pattern = "%H%M%S.%f"
epoch = int(time.mktime(time.strptime(out_ts, pattern))
print 'epoch'

這是我要轉換的時間的示例:

82128.668173

我是Python的新手,將不勝感激!

strptime()函數將字符串轉換為時間或日期,因此,如果out_ts是浮點數,則首先需要將其轉換為字符串,例如:

>>> out_ts = 82128.668173
>>> time.strptime(str(out_ts), '%H%M%S.%f')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=21, tm_sec=28, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>> datetime.strptime(str(out_ts), '%H%M%S.%f')
datetime.datetime(1900, 1, 1, 8, 21, 28, 668173)

但是,您將無法將這些日期轉換為紀元時間,因為紀元時間是自1970年1月1日起經過的秒數,並且因為out_ts僅包含小時/分鍾/秒信息,所以您將獲得1900年的日期/時間。

您將需要澄清要計算日期時間的日期。 此示例的時間為8:21:28,但是您是否要在1970年1月1日,今天的日期或其他某個日期使用該時間?

將任意日期添加到您的時間的一種簡單方法是使用代表您的時間的datetime.timedelta對象,然后將其添加到您想要的日期的datetime對象中,例如:

>>> from datetime import datetime, timedelta
>>> out_ts = 82128.668173
>>> dt = datetime.strptime(str(out_ts), '%H%M%S.%f')
>>> td = timedelta(hours=dt.hour, minutes=dt.minute, seconds=dt.second)
>>> td
datetime.timedelta(0, 30088)
>>> date = datetime(2012, 2, 13)
>>> full_time = date + td
>>> full_time
datetime.datetime(2012, 2, 13, 8, 21, 28)
>>> epoch = time.mktime(full_time.timetuple())
>>> epoch
1329150088.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM