[英]converting a date string to date format then do subtraction
I am given two dates as string below, and I want to subtract to get a number 16 as my output.下面给出了两个日期作为字符串,我想减去得到一个数字 16 作为我的 output。 i tried convert them to date format first and do the math but it didn't work.我尝试先将它们转换为日期格式并进行数学运算,但它没有用。 Thanks in advance提前致谢
from datetime import datetime从日期时间导入日期时间
date_string = '2021-05-27' date_string = '2021-05-27'
prev_date_string = '2021-05-11' prev_date_string = '2021-05-11'
a= datetime.strptime(date_string '%y/%m/%d') a= datetime.strptime(date_string '%y/%m/%d')
b =datetime.strptime(prev_date_string '%y/%m/%d') b =datetime.strptime(prev_date_string '%y/%m/%d')
c= ab c = ab
print (c)打印 (c)
There are two problems with the strptime
calls. strptime
调用有两个问题。 First, they are missing commas ( ,
) between the two arguments.首先,它们在两个 arguments 之间缺少逗号 ( ,
)。 Second, the format string you use must match the format of the dates you have.其次,您使用的格式字符串必须与您拥有的日期格式相匹配。
Also, note the result of subtracting two datetime
objects is a timedelta
object .另外,请注意减去两个datetime
对象的结果是timedelta
object 。 If you just want to print out the number 16, you'll need to extract the days
property of the result:如果您只想打印数字 16,则需要提取结果的days
属性:
a = datetime.strptime(date_string, '%Y-%m-%d')
b = datetime.strptime(prev_date_string, '%Y-%m-%d')
c = a-b
print (c.days)
The simple answer for this problem.这个问题的简单答案。
from datetime import date
a = date(2021, 5, 11)
b = date(2021, 5, 27)
c = b - a
print(c.days)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.