Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two dates (datetime)

I'm trying to write a program in Python that calculates the number of days between two dates.

I'm getting input from the user in the format May 2 2020. I have learned that I should first parse a string to a date, but I don't know how to do that. Please help me.

Here is the program I have tried:

from datetime import date

first_date(input)
sec_date(input)
con_date = datetime.strptime(first_date, '%d %m %Y').date()
con_date2 = datetime.strptime(first_date, '%d %m %Y').date()
delta = con_date2 - con_date
print(delta)

If I give input in the form of string May 2 2020 for the first_date and Jun 30 2020 for the sec_date, how can I convert this string into date format? Note: input should be given in the above format only.

The above code is not working for me to convert a string to a date. Please help me convert it into date and find the number of days between sec_date to first_date.

like image 679
Ashok Kumar Avatar asked Sep 12 '25 12:09

Ashok Kumar


2 Answers

You can simply parse the time using the appropriate strptime format.

Then, once you’ve obtained two date objects, you can simply subtract them:

import datetime 

d1_str = "Apr 29 2020"
d2_str = "May 7 2020"

fmt = "%b %d %Y"

d1 = datetime.datetime.strptime(d1_str, fmt).date()
d2 = datetime.datetime.strptime(d2_str, fmt).date()

delta = d2 - d1
print(delta)
print(delta.days)

Output is:

6 days, 0:00:00
6
like image 124
NicholasM Avatar answered Sep 14 '25 02:09

NicholasM


from datetime import datetime

first_date = "May 2 2020"
sec_date = "Jun 30 2020"
con_date = datetime.strptime(first_date, '%b %d %Y').date()
con_date2 = datetime.strptime(sec_date, '%b %d %Y').date()
delta = con_date2 - con_date
print(delta.days)
like image 34
305Curtis Avatar answered Sep 14 '25 02:09

305Curtis