Given a specific datetime, how do I subtract it by day? - python

I'm aware of how to subtract the current date from a day datetime.datetime.now() - timedelta(days=n_days), but how do I subtract a specific day (datetime format) from a number of days?
Thanks in advance.
I tried subtracting the datetime directly from timedelta(days=n_days), but it gave a type error.
what I got:
difference = a_datetime - timedelta(days=n_days)
but it gave a type error.
expected result
difference = something - timedelta(days=n_days)
should result the date n days from date something

Below code works:
import datetime
dt = datetime.date(2019, 1, 23)
print dt
new_dt = dt - datetime.timedelta(days=1)
print new_dt
Output:
2019-01-23
2019-01-22
Speculation: You seem to be missing a datetime before timedelta in your code

Are you sure you want to subtract a datetime from a number of days? Think about it: You're trying to do:
e.g: 203 days - now
203 - 12/02/2019
Interpret current date as days?
203 - 737510.75
= -737307.75

Related

Get age from timestamp

I have a dataframe with timestamp of BirthDate = 2001-10-10 11:01:04.343
How can I get an actual age?
I tried like that:
i.loc[0, "BirthDate"] = pd.to_datetime('today').normalize() - i.loc[0, "BirthDate"].normalize()
output is: 7248 days 00:00:00
but is there any better method which give me just output 19 years?
If i use:
(i.loc[0, "BirthDate"] = pd.to_datetime('today').normalize() - i.loc[0, "BirthDate"].normalize())/365
the output is:
19 days 20:34:50:958904109 and it is type <class 'pandas.timedeltas.Timedelta>
The timedelta result is wrong because you are dividing by 365 where you shouldn't. It actually means 19.86 years.
In some more detail, you are taking a value which is in years, and dividing it with 365; so now you have a result which shows 1/365 of the input duration. The proper way to get the result in years is to divide by another timedelta.
>>> from datetime import timedelta
>>> t = timedelta(days=7248)
>>> 7248/365.0
19.85753424657534
>>> print(t)
7248 days, 0:00:00
>>> t/timedelta(days=365)
19.85753424657534
>>> # years
How exactly to represent a year is not completely well-defined. You could use timedelta(days=365.2425) for the arithmetically correct length of a year, but then of course that produces odd results if you try to convert that back to a resolution where hours and minutes are important.
First, delete the last part of the timestamp and then the following python code can be applied:
from datetime import datetime, date
def calculate_age(born):
born = datetime.strptime(born, "%d/%m/%Y").date()
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
df['Age'] = df['Date of birth'].apply(calculate_age)
print(df)

subtract one day from timestamp - python

'I'm trying to subtract a day from this date 1590074712 in order to make 1590008151 but can't figure out any way to achieve that.
I've tried with:
from datetime import datetime
ts= 1590074712
date = datetime.timestamp(ts) - timedelta(days = 1)
print(date)
How can I subtract a day from a date in the above format?
I want the output in timestamp
Use datetime.fromtimestamp():
from datetime import datetime, timedelta
ts= 1590074712
date = datetime.fromtimestamp(ts) - timedelta(days = 1)
print(date)
Prints:
2020-05-20 15:25:12

Subtract one day using datetime is changing the month

I am using the datetime.datetime.timedelta to subtract a day from today. When I run the code it is changing the Month part of the Datetime class property for some reason. Please help explain.
days_to_subtract = 1
date = (datetime.datetime.today() - datetime.timedelta(days=days_to_subtract))
I expect the result for it to be 2/10/2019, but the output gives 10/02/2019.
import datetime
days_to_subtract = 1
date = (datetime.datetime.today() - datetime.timedelta(days=days_to_subtract))
print (date)
#output
2019-02-10 13:02:07.645241
print (date.strftime('%m/%d/%Y'))
#output
02/10/2019

Not understanding datetime delta in Python

from datetime import datetime as dt
I have 2 datetime fields
dt.now() returns 2019-01-08 11:46:26.035303
This is PST
x is my dataset
x['CreatedDate'] returns 2019-01-08T20:35:47.000+0000
dt.strptime(x['CreatedDate'.split('.')[0],'%Y-%m-%dT%H:%M:%S)) - datetime.timedelta(hours=8) returns 2019-01-08 08:43:33
I subtract the two,
tdelta = dt.now() - (dt.strptime(x['CreatedDate'.split('.')[0],'%Y-%m-%dT%H:%M:%S)) - datetime.timedelta(hours=8))
which is 2019-01-08 11:46:26.035303 - 2019-01-08 08:43:33
The difference should be ~3 hours but the result I'm getting is -1 day, 11:02:53.039790
-13H 12M 53S
I'm confused as to what is being returned.
Disclaimer
I am having a tough time making the datetime objects that you made. So, my answer will not be a direct solution to your exact problem.
I dont have x defined in my code. If you supply it, I can adjust my answer to be more specific.
Answer
But if you use this code:
import datetime as dt
first_time = dt.datetime(2019, 1, 8, 8, 43, 33) #This is a good way to make a datetime object
To make your datetime object then this code below will make the correct calculations and print it effectively for you:
second_time = dt.datetime.now()
my_delta = first_time - second_time
print("Minutes: " + str(my_delta.total_seconds()/60))
print("Hours: " + str(my_delta.total_seconds()/3600))
print("Days: " + str(my_delta.total_seconds()/3600/24))
Note
dt.datetime takes (year, month, day, hour, minute, second) here but dt.datetime.now() is making one with microseconds as well (year, month, day, hour, minute, second, microseconds). The function can handle being given different time specificities without error.
Note 2
If you do print(my_delta) and get something like: -1 day, 16:56:54.481901 this will equate to your difference if your difference is Hours: -7.051532805277778 This is because 24-16.95 = -7.05
The issue is with the subtraction of datetime.timedelta(hours=8) I removed that from changed the dt.now to dt.utcnow() and it works fine.

Subtracting Dates With Python

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.
from datetime import datetime
birthday = datetime(1988, 2, 19, 12, 0, 0)
diff = datetime.now() - birthday
print diff
# 8954 days, 7:03:45.765329
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.
When substracting two datetime objects you will get a new datetime.timedelta object.
from datetime import datetime
x = datetime.now()
y = datetime.now()
delta = y - x
It will give you the time difference with resolution to microsencods.
For more information take a look at the official documentation.
Create a datetime.datetime from your date:
datetime.datetime.combine(birthdate, datetime.time())
Now you can subtract it from datetime.datetime.now().
>>> from datetime import date, datetime, time
>>> bday = date(1973, 4, 1)
>>> datetime.now() - datetime.combine(bday, time())
datetime.timedelta(14392, 4021, 789383)
>>> print datetime.now() - datetime.combine(bday, time())
14392 days, 1:08:13.593813
import datetime
born = datetime.date(2002, 10, 31)
today = datetime.date.today()
age = today - born
print(age.total_seconds())
Output: 463363200.0
Since DateTime.DateTime is an immutable type method like these always produce a new object the difference of two DateTime object produces a DateTime.timedelta type:
from datetime import date,datetime,time,timedelta
dt=datetime.now()
print(dt)
dt2=datetime(1997,7,7,22,30)
print(dt2)
delta=dt-dt2
print(delta)
print(int(delta.days)//365)
print(abs(12-(dt2.month-dt.month)))
print(abs(dt.day))
The output timedelta(8747,23:48:42.94) or what ever will be days when u test the code indicates that the time delta encodes an offset of 8747 days and 23hour and 48 minute ...
The Output
2021-06-19 22:27:36.383761
1997-07-07 22:30:00
8747 days, 23:57:36.383761
23 Year
11 Month
19 Day

Categories