我正在尝试用 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:两次之间的差异
发布评论