Python:两次之间的差异

编程入门 行业动态 更新时间:2024-10-28 18:26:29
本文介绍了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:两次之间的差异

本文发布于:2023-10-27 03:55:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532236.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   差异   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!