有很多关于查找两个日期之间差异的帖子,但所涉及的值以与我使用的格式不同的格式开始和结束,例如:
a = 01/01/10 # dd/mm/yy format
b = 01/01/05 # dd/mm/yy format
因此,我在 a 和 b 之间的年、月和日之间存在差异,其中所需的输出采用格式x years, x months, x days (if required)
格式。
我正在阅读datetime 文档,并且想弄清楚它(注意:前面的新手代码,我试图拼凑所有的演示,所以不得不做一些修改):
from datetime import datetime as dt
# calculate duration between two dates
# later date
later_date = '01/01/10'.replace('/', '')
# reverse the order
later_date = "".join(reversed([later_datet[i:i+2] for i in range(0, len(later_date), 2)]))
# separate with commas every two numbers
later_date = ','.join(later_date[i:i+2] for i in range(0, len(later_date), 2))
# convert to datetime object
later_date = dt.strptime(later_date, "%y,%m,%d")
# earlier date
earlier_date = '01/01/05'.replace('/','')
# reverse the order
earlier_date = "".join(reversed([earlier_date[i:i+2] for i in range(0, len(earlier_date), 2)]))
# separate with commas every two numbers
earlier_date = ','.join(earlier_date[i:i+2] for i in range(0, len(earlier_date), 2))
# convert to datetime object
earlier_date = dt.strptime(earlier_date, "%y,%m,%d")
duration = later date - earlier_date
print duration
print type(duration)
正在输出:
1826 days, 0:00:00
<type 'datetime.timedelta'>
所以我认为我有点接近获得正确的数据,但现在我需要将其转换为x years, x months, x days (if required)
格式。
编辑/解决方案:
我已经将一些代码放在一起并正在测试,我认为它适用于所有日期组合,但如果有人注意到错误,请告诉我:
"""
this code calculates the duration between two dates (a later and earlier date)
in the format dd/mm/yy and returns the duration in years, months and days with
correct formatting in regards to the plurality of the year/s, month/s, and day/s
and the punctuation required dependent on whether one or more values are returned
ie multiple values are separated by ',' whereas a singular value is terminated by '.'.
"""
# imported libraries
from datetime import datetime as dt
from dateutil import relativedelta
import sys
# initial date objects
later_date = '01/01/10'
earlier_date = '01/01/05'
# convert dates to required format
a_date = dt.strptime(later_date, '%d/%m/%y')
b_date = dt.strptime(earlier_date, '%d/%m/%y')
# get duration using dateutil
duration = relativedelta.relativedelta(a_date, b_date)
# check if number of years is not false ie != 0
if duration.years != 0:
years = duration.years
else:
years = False
# check if number of months is not false ie != 0
if duration.months != 0:
months = duration.months
else:
months = False
# check if number of days is not false ie != 0
if duration.days != 0:
days = duration.days
else:
days = False
# add values to a list
date_list = [years,months,days]
# count instances of False in the list
false_count = date_list.count(False)
# iterate over list with enumeration performing value and
# boolean checking to predicate plurality and punctuality
# requirements.
for n, _ in enumerate(date_list):
# year/s - single or plural, lone value or more
if _ != False and n == 0:
single_year = date_list[0] == 1
# if single and not lone
if single_year == True and false_count != 2:
sys.stdout.write(str(_)+' year, ')
# if single and lone
elif single_year == True and false_count == 2:
sys.stdout.write(str(_)+' year.')
# if not single and not lone
elif single_year == False and false_count != 2:
sys.stdout.write(str(_)+' years, ')
# if not single but lone
elif single_year == False and false_count == 2:
sys.stdout.write(str(_)+' years.')
# if there are no years, still provide value for possible later concatenation
if _ == False and n == 0:
datasetduration_y = ''
# month/s - single or plural, lone value or more
if _ != False and n == 1:
single_month = date_list[1] == 1
# if single and not lone
if single_month == True and false_count != 2:
sys.stdout.write(str(_)+' month, ')
# if single and lone
elif single_month == True and false_count == 2:
sys.stdout.write(str(_)+' month.')
# if not single and not lone and there are days
elif single_month == False and false_count != 2 and date_list[2] != False:
sys.stdout.write(str(_)+' months, ')
# if not single and not lone and there are no days
elif single_month == False and false_count != 2 and date_list[2] == False:
sys.stdout.write(str(_)+' months.')
# if not single but lone
elif single_month == False and false_count == 2:
sys.stdout.write(str(_)+' months.')
# if there are no months, still provide value for possible later concatenation
if _ == False and n == 1:
datasetduration_m = ''
# day/s - single or plural, lone value or more
if _ != False and n == 2:
single_day = date_list[2] == 1
# if single and not lone
if single_day == True and false_count != 2:
sys.stdout.write(str(_)+' day.')
# if single and lone
elif single_day == True and false_count == 2:
sys.stdout.write(str(_)+' day.')
# if not single and not lone
elif single_day == False and false_count != 2:
sys.stdout.write(str(_)+' days.')
# if not single but lone
elif single_day == False and false_count == 2:
sys.stdout.write(str(_)+' days.')
# if there are no days, still provide value for possible later concatenation
if _ == False and n == 2:
datasetduration_d = ''