首页 > python计算时间差

python计算时间差

需要处理的时间文本格式如下:
2001-10-09 15:12:15
2001-10-31 18:41:59
2001-10-31 18:50:27
2001-11-11 18:28:26
2001-11-11 18:28:54
2001-11-12 06:18:34
2001-11-17 03:36:20
然后需要以一个的时间为计算标准,计算后面所有行的时间跟第一行时间的时间差并输出,假设第一行的时间差设置为0


当前Python版本 3.4.3

# -*- coding:utf-8 -*-

#datetime类,datetime是date与time的结合体,包括date与time的所有信息。
#从datetime中导入datetime类
from datetime import datetime

#python中三引号是多行字符串
str = '''2009-10-09 0:0:0
2009-10-10 3:2:1'''.split("\n")

def string_to_date(date_string):
    date_format = '%Y-%m-%d %H:%M:%S'
    #将格式字符串转换为datetime对象;将传进来的参数date_string转换为格式字符串  
    #函数.strip()删除date_string中字符串中开头、结尾处,空字符的内容
    return datetime.strptime(date_string.strip(), date_format)
start_date = string_to_date(str[0])

#从第二个开始遍历
for date_string in str[1:]:
    print (string_to_date(date_string) - start_date)

可以用標準庫中的 datetime:

from datetime import datetime, timedelta

with open('data', 'r') as f:
    datetimes = [datetime.strptime(line.strip(), "%Y-%m-%d %H:%M:%S") for line in f]

def get_dhms(td):
    """
    given a timedelta then return corresponding days/hours/minutes/seconds 
    """
    seconds = td.total_seconds()
    # return seconds/86400, seconds/3600, seconds/60, seconds  # 如果不捨去小數點,用此行
    return seconds//86400, seconds//3600, seconds//60, seconds

for dt in datetimes[1:]:
    td = (dt - datetimes[0])
    print dt, 'vs', datetimes[0], '->', get_dhms(td)

測試資料 data:

2001-10-09 15:41:54
2001-10-19 15:41:55
2001-10-29 15:42:54
2001-10-31 06:00:55
2002-01-01 23:59:59
2011-01-01 23:59:59

結果:

2001-10-19 15:41:55 vs 2001-10-09 15:41:54 -> (10.0, 240.0, 14400.0, 864001.0)
2001-10-29 15:42:54 vs 2001-10-09 15:41:54 -> (20.0, 480.0, 28801.0, 1728060.0)
2001-10-31 06:00:55 vs 2001-10-09 15:41:54 -> (21.0, 518.0, 31099.0, 1865941.0)
2002-01-01 23:59:59 vs 2001-10-09 15:41:54 -> (84.0, 2024.0, 121458.0, 7287485.0)
2011-01-01 23:59:59 vs 2001-10-09 15:41:54 -> (3371.0, 80912.0, 4854738.0, 291284285.0)

函數 get_dhms 會吃進一個 timedelta(時間差) 參數,並且回傳一個 4 元素 tuple 分別是這個 時間差 轉換出來的:

(日數,小時數,分鐘數, 秒數)

from datetime import datetime

text_list = '''2001-10-09 15:12:15
2001-10-31 18:41:59
2001-10-31 18:50:27
2001-11-11 18:28:26
2001-11-11 18:28:54
2001-11-12 06:18:34
2001-11-17 03:36:20'''.split("\n")

def string_to_date(date_string):
    date_format = '%Y-%m-%d %H:%M:%S'
    return datetime.strptime(date_string.strip(), date_format)
   
start_date = string_to_date(text_list[0])

for date_string in text_list[1:]:
    print string_to_date(date_string) - start_date
    print (string_to_date(date_string) - start_date).total_seconds()
    

具体的格式可以参考 文档

【热门文章】
【热门文章】