简体   繁体   English

获取 Python 中两个日期之间的平均天数

[英]Get the average number of days between two dates in Python

I have a data frame with only dates in one column.我有一个数据框,一列中只有日期。 My objective is to calculate the number of days between each date, in order to get the average number of days between two dates (each date corresponds to an operation).我的目标是计算每个日期之间的天数,以获得两个日期之间的平均天数(每个日期对应一个操作)。

I tried doing something like this:我试着做这样的事情:

for i in range(len(df)):
    if i != 0:
        d0 = df.iloc[[i-1,1]]
        d1 = df.iloc[[i,1]]
        L.append((d1 - d0).days)

But got the error message: 'unsupported operand type(s) for -: 'str' and 'str''但收到错误消息:'unsupported operand type(s) for -:'str' and 'str''

You can subtract a date from another if they're in proper format.如果格式正确,您可以从另一个日期中减去一个日期。 Maybe a timestamp in seconds, maybe a proper datetime object.也许是一个以秒为单位的时间戳,也许是一个适当的datetime时间 object。 As you might've noticed, you can't subtract strings.您可能已经注意到,您不能减去字符串。

If the date is in the ISO format, it's the easiest, just do this before the subtraction:如果日期是 ISO 格式,这是最简单的,只需在减法之前执行此操作:

from datetime import datetime
d0 = datetime.fromisoformat(d0)
d1 = datetime.fromisoformat(d1)

The result will be in a datetime.timedelta format with a .total_seconds() method and even a .days attribute, so you get days like this:结果将采用带有.total_seconds()方法甚至.days属性的datetime.timedelta格式,因此您会得到这样的天数:

difference_in_days = (d1 - d0).days

If it's something else than an ISO string, check out this question: Converting string into datetime如果它不是 ISO 字符串,请查看以下问题: Converting string into datetime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM