Python:两次之间的差异 [英] Python: Difference between two times

查看:54
本文介绍了Python:两次之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 Python 计算两个日期之间的差异,并以天、周、月和年表示这个时差.

I am trying to calculate the difference between two dates in Python, and express this time difference in days, weeks, months and years.

我的Python代码如下:

My Python code is as follows:

    purDate = datetime.datetime.strptime(queryPurchaseDate (purID), "%Y-%m-%d %H:%M:%S")
    now = datetime.datetime.now()

    print 'Purchase date/time : ',purDate.strftime("%Y-%m-%d %H:%M:%S")
    print 'Current date/time : ',now.strftime("%Y-%m-%d %H:%M:%S")

    hold = now - purDate    

    print hold

这段代码的结果如下:

bash-3.2$ ./test.py 
Purchase date/time :  2017-10-10 00:00:00
Current date/time :  2017-10-14 17:33:39
4 days, 17:33:39.866069
bash-3.2$

而不是将两个日期之间的差异表示为4 天,17:33:39.866069我想表达如下:4.65 天,或0.66 周,或0.15 个月,或0.01年

Instead of having the difference between the two date expressed as 4 days, 17:33:39.866069 I would like to have it expressed as follows: 4.65 Days, or 0.66 Weeks, or 0.15 Months, or 0.01 Years

推荐答案

可以使用pandas转换为timedelta对象,然后进行后续的数学运算

You can convert to a timedelta object using pandas and then perform the subsequent mathematical operation

delta = pd.Timedelta(delta)
delta.total_seconds()/(24*60*60) # this will give the timedelta in days

演示

import pandas as pd
import datetime

time1 = datetime.datetime.now()
time2 = '2017-10-01 00:00:00'
time2 = pd.to_datetime(time2)

delta = time1 - time2
print(delta)
13 days 22:03:50.081000

delta = pd.Timedelta(delta)
print(delta.total_seconds()/(24*60*60))
13.909289537037038

无需使用熊猫.正如@Reti43 解释的那样,您可以只使用 delta.total_seconds()/(24*60*60)

No need to use pandas. As @Reti43 explains, you can just use delta.total_seconds()/(24*60*60)

这篇关于Python:两次之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆