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
Related
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)
I am adding 2 days in current date or today date using python but getting wrong output, please at look at code below i used ::
from datetime import date
from datetime import timedelta
time_diff =str(timedelta(days=2))
d =str(date.today().strftime("%Y-%m-%d") ) + time_diff
print(d.split("day")[0])
OUTPUT ::2020-04-262
i think it should show the output ::2020-04-28.
You don't need all those str() calls. You want to add the time delta to a time, you don't want to add two strings together (that just concatenates).
Just add the time delta to the date:
from datetime import timedelta
time_diff = timedelta(days=2)
a_date = date.today() + time_diff
a_date_string = a_date.strftime("%Y-%m-%d")
print(a_date_string)
# 2020-04-28
My Date should always fall on 8th or 22nd that comes off the input date.
For Example:
If the input date is 20190415 then the output date should be 20190422 as that's the nearest date and if input date is 20190424 then the output date should be 20190508.
Example1:
input_date = 20190415
Expected output_date = 20190422
Example2:
input_date = 20190424
Expected output_date = 20190508
Example3:
input_date = 20190506
Expected output_date = 20190508
Example4:
input_date = 20191223
Expected output_date = 20200108
How do we achieve this using Python?
You can check if the day is greater than 22, and if so you set it to the 8th of the next month. If it's between 8 and 22 you set it to 22 of the same month and if it's below the 8th you set it to the 8th of the month. There's probably more elegant ways to do it using date math, but this will work for your scenario.
Use the datetime module to find out what the "next month" is. One way to do it is to add a timedelta of 1 month to the first of the current month, and then change the date on that datetime object to the 8th. Here's a quick example of how that might look like:
from datetime import date, timedelta
input_date = date(2019, 12, 23)
if input_date.day > 22:
output_date = date(input_date.year, input_date.month) + timedelta(days=31)
output_date = output_date.replace(day = 8)
You can read a lot more about the details of how the datetime module works on the official documentation. It's kind of a long read, but I actually have that page bookmarked because I always have to go back and reference how to actually use the module :)
Considering the input as string, next date can be calculated using timedelta, check out the below code:
if 8<datetime.strptime(input_date, "%Y%m%d").day < 22:
delta = 22 - datetime.strptime(input_date, "%Y%m%d").day
print((datetime.strptime(input_date, "%Y%m%d") +
timedelta(days=delta)).strftime("%Y%m%d"))
elif datetime.strptime(str(input_date), "%Y%m%d").day < 8:
delta = 8 - datetime.strptime(input_date, "%Y%m%d").day
print((datetime.strptime(input_date, "%Y%m%d") +
timedelta(days=delta)).strftime("%Y%m%d"))
else:
delta = (datetime.strptime(input_date, "%Y%m%d")+ relativedelta(months=+1)).day -8
print((datetime.strptime(input_date, "%Y%m%d") + relativedelta(months=+1) -
timedelta(days=delta)).strftime("%Y%m%d") )
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
I need help with a program.
How do I add 3 weeks (21 days) to any given date when the user can control the date?
The user will enter the date YYYY-MM-DD.
Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:
date = raw_input("Enter date: ")
i = 0
while i <= len(date):
if date[i] != "-":
i = i + 1
print date
Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?
year = date[0:4]
month = date[5:7]
day = date[9:11]
thanks
Use datetime module to the task. You create a datetime aware object and add 21 days timedelta object to it.
>>> import datetime
>>> u = datetime.datetime.strptime("2011-01-01","%Y-%m-%d")
>>> d = datetime.timedelta(days=21)
>>> t = u + d
>>> print(t)
2011-01-22 00:00:00
You can use a datetime.timedelta object to represent 3 weeks and then just add that to the datetime object that represents the user's input.
import datetime
date = raw_input("Enter date: ")
aDate = datetime.datetime.strptime(date,"%Y-%m-%d")
threeWeeks = datetime.timedelta(weeks = 3)
print aDate + threeWeeks
See http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior for details about using the strptime method.
Try this, I am sure its the shortest and easiest way to go
from dateutil.relativedelta import relativedelta
period = date.today() + relativedelta(weeks=+1)
you can use datetime.strptime to get input from user as date
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
print "Incorrect format"
and then to add 3 weeks (21 days)
dt_start = dt_start + datetime.timedelta(days=21)
There you go