Python count start date + days - python

I am making a program where I input start date to dataStart(example 21.10.2000) and then input int days dateEnd and I convert it to another date (example 3000 = 0008-02-20)... Now I need to count these dates together, but I didn't managed myself how to do that. Here is my code.
from datetime import date
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
dataStart=start.split(".")
days=int(dataStart[0])
months=int(dataStart[1])
years=int(dataStart[2])
endYears=0
endMonths=0
endDays=0
dateStart = date(years, months, days)
while end>=365:
end-=365
endYears+=1
else:
while end>=30:
end-=30
endMonths+=1
else:
while end>=1:
end-=1
endDays+=1
dateEnd = date(endYears, endMonths, endDays)

For adding days into date, you need to user datetime.timedelta
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
date = datetime.strptime(start, "%d.%m.%Y")
modified_date = date + timedelta(days=end)
print(datetime.strftime(modified_date, "%d.%m.%Y"))

You may use datetime.timedelta to add certain units of time to your datetime object.
See the answers here for code snippets: Adding 5 days to a date in Python
Alternatively, you may wish to use the third-party dateutil library if you need support for time additions in units larger than weeks. For example:
>>> from datetime import datetime
>>> from dateutil import relativedelta
>>> one_month_later = datetime(2017, 5, 1) + relativedelta.relativedelta(months=1)
>>> one_month_later
>>> datetime.datetime(2017, 6, 1, 0, 0)

It will be easier to convert to datetime using datetime.datetime.strptime and for the part about adding days just use datetime.timedelta.
Below is a small snippet on how to use it:
import datetime
start = "21.10.2000"
end = 8
dateStart = datetime.datetime.strptime(start, "%d.%m.%Y")
dateEnd = dateStart + datetime.timedelta(days=end)
dateEnd.date() # to get the date format of the endDate
If you have any doubts please look at the documentation python3/python2.

Related

How do I calculate the date Three months from a input date using python

I am using the datetime Python module. I am looking to calculate the date 3 months from the input date. Can you help me to get out of this issue.Thanks in advance
import datetime
today = "2022-02-24"
three = today + datetime.timedelta(30*3)
print (three)
Also I tried using "relativedelta"
You can't add a timedelta to a string, you need to add it to a datetime instance
Note that 90 days, isn't really 3 months
from datetime import datetime, timedelta
today = "2022-02-24"
three = datetime.strptime(today, "%Y-%m-%d") + timedelta(30 * 3)
print(three) # 2022-05-25 00:00:00
three = datetime.today() + timedelta(30 * 3)
print(three) # 2022-05-24 21:32:35.048700
With relativedelta of dateutil package, you can use:
from dateutil.relativedelta import relativedelta
from datetime import date
three = date.today() + relativedelta(months=3)
Output:
>>> three
datetime.date(2022, 5, 23)

How to convert a 'day/month' string to date in python and compare it with an Odoo date field?

I have a day/month string, I want to convert that string to date object and compare the last day of that month to another date
Example:
For 08/2021 (august, 2021) I want to compare the last day of that month (31-08-2021) to another date (date field),
For 02/2020 I what to compare 29-02-2020 < another_date (date field)
For 02/2021 I what to compare 28-02-2020 < another_date (date field)
You can use calendar.monthrange to find the last day in the month if you don't want to add dateutil.
import calendar
from datetime import datetime
def get_last_day_date(year_month_str):
date = datetime.strptime(year_month_str, "%m/%Y")
last_day = calendar.monthrange(date.year, date.month)[1]
return datetime(date.year, date.month, last_day)
get_last_day_date("08/2020")
# datetime.datetime(2020, 8, 31, 0, 0)
This examples shows you how to convert '02/2020' to a Python datetime and how to get the last day of that month. You can use it to compare the result to another datetime:
import datetime
from dateutil.relativedelta import relativedelta
date = '02/2020'
last_day = datetime.datetime.strptime(date, '%m/%Y') + relativedelta(day=31)
# last_day will be a datetime of the last day of the month which you can use to compare against another datetime
In this example, the result is datetime.datetime(2020, 2, 29, 0, 0) because 2020 was a leap year
b='08/2021'
a=b.split('/')
import calendar
import datetime
z=(str(calendar.monthrange(int(a[1]),int(a[0]))[1])+'-'+b.replace('/','-'))
d=datetime.datetime.strptime(z,'%d-%m-%Y').date()
print(d)
n=datetime.date.today()
print(n)
n<d
Output:
2021-08-31
2021-01-28
True
It can be done by just importing/using datetime library and here you can see how.
By passing string date into method.
import datetime
def convert_string_to_datetime(self, datetime_in_string):
datetime_in_string = str(datetime_in_string)
datetime_format = "%Y-%m-%d %H:%M:%S"
datetime_in_datetime_format = datetime.datetime.strptime(datetime_in_string, datetime_format)
return datetime_in_datetime_format
new_datetime_field = convert_string_to_datetime(datetime_in_string)
By modifying with in single line
import datetime
new_datetime_field = datetime.datetime.strptime(YOUR_DATETIME_IN_STRING, "%Y-%m-%d %H:%M:%S")
After converting into datetime now comparison is possible like.
if new_datetime_field > odoo_datetime_field:
pass

Compare current date with future date in Python

I am trying to compare the current date in the following format (ddmmyyyy) to a future date in the following format (ddmmyyyy)
I put them in that format so i can easily compare them as integers. However, it keeps failing the if then test.
from datetime import datetime, timedelta
StartDay=datetime.today() # Get current date in this format 2020-04-28 19:59:16.901897
EndDay=StartDay+timedelta(60) # I want to be able to add 60 days to StartDay
print(EndDay.strftime('%d%m%Y')) # Print EndDay as an integer 27062020
EndDay=EndDay.strftime('%d%m%Y') # Convert EndDay to make it look like an integer
StartDay=datetime.today().strftime('%d%m%Y') # Convert the StartDay to make it look like an integer
if int(StartDay)>int(EndDay):
print('Game Over!')
else:
pass
What I want to achieve is the an integer value for a date, such that the future date will always be greater than past/current date if that makes sense.
you can directly compare datetime objects, no need for a detour here:
from datetime import datetime
t0, t1 = datetime(2020,1,1), datetime(2020,1,2)
t0>t1
Out[6]: False
t0<t1
Out[7]: True
t1-t0
Out[8]: datetime.timedelta(days=1)
datetime.datetime might be easily converted into datetime.date and then compared consider following example:
from datetime import datetime, timedelta
StartDay = datetime.today()
EndDay = StartDay + timedelta(60)
StartDate = StartDay.date() # datetime.date(2020, 4, 28)
EndDate = EndDay.date() # datetime.date(2020, 6, 27)
print(StartDate < EndDate) # True
Note that you might also compare datetime.datetime directly with datetime.datetime but this take in account also units smaller than days, so if you have two datetime.datetimes say d1 and d2 with same year-month-day but different hours, then result of d1 < d2 might be different from d1.date() < d2.date()
Keep startdate and enddate as 'datetime' and do the following:
from datetime import datetime, timedelta
StartDay=datetime.today()
EndDay=StartDay+timedelta(60)
delta = (StartDay - EndDay).days
if delta > 0:
print('Game Over!')
else:
print('Something else')
This should do the trick

Python construct datetime having weekday with other time parameters

I need to construct datetime object from different parameters. For example, I get these parameters:
integer number from 0 to 6. This one indicates weekday.
hour and minutes in float format (from 0.0 to 24.0).
And then I know which week of the current year it is going to be. So, for example, let say that datetime should be from 2014-07-18 00:00:00 to 2014-07-24 23:59:00 (seconds can be ignored and left at 00). So to get exact datetime I need to use above defined parameters.
Let say I would get these parameters 4 (meaning Friday), and 9.5 (meaning 09:30).
So by doing such construction, I should get a date that would be: 2014-07-22 09:30:00. How could accomplish such thing?
Do I need to somehow get for example day of the month by knowing which is the week of the year and which weekday it is?
P.S. A bit more detailed example of what I'm trying to accomplish
from datetime import datetime
today = datetime.today() #using this to get the week I'll be working with.
today = today.replace(day=?) #how to get which day I
#need to enter by having weekday and knowing that week is the present one?
You could do something like that, if your parameters are weekday and t (time):
from datetime import timedelta
monday = today - timedelta(days=today.weekday())
result = (monday + timedelta(days=weekday)).replace(hour=int(t), minutes=int((t - int(t)) * 60))
If you have a starting date, use the relative value of the datetime.datetime.weekday() value to construct a timedelta() object that'll put you onto the right weekday, then replace the hour and minutes:
from datetime import timedelta
def relative_date(reference, weekday, timevalue):
hour, minute = divmod(timevalue, 1)
minute *= 60
days = reference.weekday() - weekday
return (reference - timedelta(days=days)).replace(
hour=int(hour), minute=int(minute), second=0, microsecond=0)
Demo:
>>> from datetime import timedelta, datetime
>>> def relative_date(reference, weekday, timevalue):
... hour, minute = divmod(timevalue, 1)
... minute *= 60
... days = reference.weekday() - weekday
... return (reference - timedelta(days=days)).replace(
... hour=int(hour), minute=int(minute), second=0, microsecond=0)
...
>>> relative_date(datetime.now(), 4, 9.5)
datetime.datetime(2014, 8, 22, 9, 30)
>>> relative_date(datetime.now() - timedelta(days=30), 6, 11.75)
datetime.datetime(2014, 7, 27, 11, 45)
I would use timedelta to add the difference between weekdays to the datetime
from datetime import datetime, timedelta
friday = 4
today = datetime.now()
friday_this_week = today + timedelta(friday - today.weekday())
In your case just replace today with a date that is in the week you want.

Get date from week number

Please what's wrong with my code:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d, "%Y-W%W")
print(r)
Display "2013-01-01 00:00:00", Thanks.
A week number is not enough to generate a date; you need a day of the week as well. Add a default:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")
print(r)
The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:
2013-07-01 00:00:00
%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.
See the strftime() and strptime() behaviour section in the documentation, footnote 4:
When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.
Note, if your week number is a ISO week date, you'll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.
In Python 3.8 there is the handy datetime.date.fromisocalendar:
>>> from datetime import date
>>> date.fromisocalendar(2020, 1, 1) # (year, week, day of week)
datetime.date(2019, 12, 30, 0, 0)
In older Python versions (3.7-) the calculation can use the information from datetime.date.isocalendar to figure out the week ISO8601 compliant weeks:
from datetime import date, timedelta
def monday_of_calenderweek(year, week):
first = date(year, 1, 1)
base = 1 if first.isocalendar()[1] == 1 else 8
return first + timedelta(days=base - first.isocalendar()[2] + 7 * (week - 1))
Both works also with datetime.datetime.
To complete the other answers - if you are using ISO week numbers, this string is appropriate (to get the Monday of a given ISO week number):
import datetime
d = '2013-W26'
r = datetime.datetime.strptime(d + '-1', '%G-W%V-%u')
print(r)
%G, %V, %u are ISO equivalents of %Y, %W, %w, so this outputs:
2013-06-24 00:00:00
Availabe in Python 3.6+; from docs.
import datetime
res = datetime.datetime.strptime("2018 W30 w1", "%Y %W w%w")
print res
Adding of 1 as week day will yield exact current week start. Adding of timedelta(days=6) will gives you the week end.
datetime.datetime(2018, 7, 23)
If anyone is looking for a simple function that returns all working days (Mo-Fr) dates from a week number consider this (based on accepted answer)
import datetime
def weeknum_to_dates(weeknum):
return [datetime.datetime.strptime("2021-W"+ str(weeknum) + str(x), "%Y-W%W-%w").strftime('%d.%m.%Y') for x in range(-5,0)]
weeknum_to_dates(37)
Output:
['17.09.2021', '16.09.2021', '15.09.2021', '14.09.2021', '13.09.2021']
In case you have the yearly number of week, just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)
Another solution which worked for me that accepts series data as opposed to strptime only accepting single string values:
#fw_to_date
import datetime
import pandas as pd
# fw is input in format 'YYYY-WW'
# Add weekday number to string 1 = Monday
fw = fw + '-1'
# dt is output column
# Use %G-%V-%w if input is in ISO format
dt = pd.to_datetime(fw, format='%Y-%W-%w', errors='coerce')
Here's a handy function including the issue with zero-week.

Categories

Resources