Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting Dates With Python

Tags:

python

date

time

I'm working on a simple program to tell an individual how long they have been alive.

I know how to get the current date, and get their birthday. The only problem is I have no way of subtracting the two, I know a way of subtracting two dates, but unfortunately it does not include hours, minutes, or seconds.

I am looking for a method that can subtract two dates and return the difference down to the second, not merely the day.

like image 233
Boe Jingles Avatar asked Aug 25 '12 22:08

Boe Jingles


People also ask

How do you subtract two dates in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1.

How do you subtract two days from a date in Python?

You can use simple date arithmetic to find the number of days between two dates in Python. Define the 2 dates between which you want to find the difference in days. Then subtract these dates to get a timedelta object and examine the day's property of this object to get the required result.

How do you subtract years in Python?

The easiest way to subtract years from a date in Python is to use the dateutil extension. The relativedelta object from the dateutil. relativedelta module allows you to subtract any number of years from a date object.

How do pandas subtract day from date?

When the function receives the date string it will first use the Pandas to_datetime() function to convert it to a Python datetime and it will then use the timedelta() function to subtract the number of days defined in the days variable.


2 Answers

from datetime import datetime  birthday = datetime(1988, 2, 19, 12, 0, 0) diff = datetime.now() - birthday print diff # 8954 days, 7:03:45.765329 
like image 142
David Robinson Avatar answered Sep 20 '22 15:09

David Robinson


Use UTC time otherwise age in seconds can go backwards during DST transition:

from datetime import datetime  born = datetime(1981, 12, 2) # provide UTC time age = datetime.utcnow() - born print(age.total_seconds()) 

You also can't use local time if your program runs on a computer that is in a different place (timezone) from where a person was born or if the time rules had changed in this place since birthday. It might introduce several hours error.

If you want to take into account leap seconds then the task becomes almost impossible.

like image 44
jfs Avatar answered Sep 19 '22 15:09

jfs