简体   繁体   English

在Python中查找两个日期之间的中点日期

[英]Finding mid-point date between two dates in Python

Given dates: 给定日期:

my_guess = '2014-11-30'
their_guess = '2017-08-30'

How do I split the delta between the dates, returning the correct calendar date? 如何拆分日期之间的差异,返回正确的日历日期?

One way would be to use datetime . 一种方法是使用datetime Find the difference between two dates, halve it, and add it on the earlier date: 找出两个日期之间的差异,将其减半,并在较早的日期添加:

>>> from datetime import datetime
>>> a = datetime(2014, 11, 30)
>>> b = datetime(2017, 8 ,30)
>>> a + (b - a)/2
2016-04-15 00:00:00
from datetime import datetime
d1 = datetime.strptime(my_guess,"%Y-%m-%d")
d2 = datetime.strptime(their_guess,"%Y-%m-%d")
print d1.date() + (d2-d1) / 2 # first date plus the midpoint of the difference between d1 and d2  
2016-04-15 

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

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