Python add one day to date

How to Add One Day in Python Calendar Module

I’m very new to coding, please excuse any basic mistakes. I’ve been working on this piece of code that uses the Python calendar module to generate a start date. Everything was working well until I realised that I also needed an end date. I tried manually adding 1 to the start date, and I realised when I printed the output that this is not going to work once it gets to the end of the month. This is the incorrect output I get. Obviously, December does not have 32 days in it. Start date is 2015-12-31. End date is 2015-12-32. I’ve been reading documents on the calendar module, but I haven’t seen anything yet (that made sense to me) on how to get this working. This is what I have so far:

import requests import json import calendar cal = calendar.Calendar() for year in range(2015,2016): for month in range(1,13): monthdays = [d for d in cal.itermonthdays(year,month) if d != 0] for day in monthdays: str_year = str(year) if month < 10: str_month = "0" + str(month) # print(str_month) else: str_month = str(month) # print(str_month) if day < 10: str_StartDay = "0" + str(day) int_EndDay = day + 1 if int_EndDay < 10: str_EndDay = "0" + str(int_EndDay) else: str_EndDay = str(int_EndDay) else: str_StartDay = str(day) int_EndDay = day + 1 str_EndDay = str(int_EndDay) # print(str_day) _STARTDATE = str_year + "-" + str_month + "-" + str_StartDay _ENDDATE = str_year + "-" + str_month + "-" + str_EndDay # print(_DATE) #fun_Phase1(_DATE) print("Start date is " + _STARTDATE) print("End date is " + _ENDDATE) 

1 Answer 1

Thanks Klaus D. You've pointed me in the right direction. I ended up using datetime to solve this problem. Here is the code. Hopefully this saves someone time in the future.

import requests import json import calendar import datetime cal = calendar.Calendar() for year in range(2015,2016): for month in range(1,13): monthdays = [d for d in cal.itermonthdays(year,month) if d != 0] for day in monthdays: str_year = str(year) int_year = int(year) if month < 10: str_month = "0" + str(month) int_month = int(month) # print(str_month) else: str_month = str(month) int_month = int(month) # print(str_month) if day < 10: str_StartDay = "0" + str(day) int_day = int(day) else: str_StartDay = str(day) int_day = int(day) # print(str_day) _MYDATE = datetime.date(int_year,int_month,int_day) str_MYDATE = str(_MYDATE) print(str_MYDATE) _MYDATEPLUSONE = _MYDATE + datetime.timedelta(days=1) str_MYDATEPLUSONE = str(_MYDATEPLUSONE) print(str_MYDATEPLUSONE) print("Start date is " + str_MYDATE) print("End date is " + str_MYDATEPLUSONE) 

Источник

How to increment a datetime by one day?

Incrementing dates can be accomplished using timedelta objects:

import datetime datetime.datetime.now() + datetime.timedelta(days=1) 

All of the current answers are wrong in some cases as they do not consider that timezones change their offset relative to UTC. So in some cases adding 24h is different from adding a calendar day.

Читайте также:  CSS цвет

Proposed solution

The following solution works for Samoa and keeps the local time constant.

def add_day(today): """ Add a day to the current day. This takes care of historic offset changes and DST. Parameters ---------- today : timezone-aware datetime object Returns ------- tomorrow : timezone-aware datetime object """ today_utc = today.astimezone(datetime.timezone.utc) tz = today.tzinfo tomorrow_utc = today_utc + datetime.timedelta(days=1) tomorrow_utc_tz = tomorrow_utc.astimezone(tz) tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour, minute=today.minute, second=today.second) return tomorrow_utc_tz 

Tested Code

# core modules import datetime # 3rd party modules import pytz # add_day methods def add_day(today): """ Add a day to the current day. This takes care of historic offset changes and DST. Parameters ---------- today : timezone-aware datetime object Returns ------- tomorrow : timezone-aware datetime object """ today_utc = today.astimezone(datetime.timezone.utc) tz = today.tzinfo tomorrow_utc = today_utc + datetime.timedelta(days=1) tomorrow_utc_tz = tomorrow_utc.astimezone(tz) tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour, minute=today.minute, second=today.second) return tomorrow_utc_tz def add_day_datetime_timedelta_conversion(today): # Correct for Samoa, but dst shift today_utc = today.astimezone(datetime.timezone.utc) tz = today.tzinfo tomorrow_utc = today_utc + datetime.timedelta(days=1) tomorrow_utc_tz = tomorrow_utc.astimezone(tz) return tomorrow_utc_tz def add_day_dateutil_relativedelta(today): # WRONG! from dateutil.relativedelta import relativedelta return today + relativedelta(days=1) def add_day_datetime_timedelta(today): # WRONG! return today + datetime.timedelta(days=1) # Test cases def test_samoa(add_day): """ Test if add_day properly increases the calendar day for Samoa. Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00 to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its local time. See https://stackoverflow.com/q/52084423/562769 A common wrong result here is 2011-12-30T23:59:00-10:00. This date never happened in Samoa. """ tz = pytz.timezone('Pacific/Apia') today_utc = datetime.datetime(2011, 12, 30, 9, 59, tzinfo=datetime.timezone.utc) today_tz = today_utc.astimezone(tz) # 2011-12-29T23:59:00-10:00 tomorrow = add_day(today_tz) return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00' def test_dst(add_day): """Test if add_day properly increases the calendar day if DST happens.""" tz = pytz.timezone('Europe/Berlin') today_utc = datetime.datetime(2018, 3, 25, 0, 59, tzinfo=datetime.timezone.utc) today_tz = today_utc.astimezone(tz) # 2018-03-25T01:59:00+01:00 tomorrow = add_day(today_tz) return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00' to_test = [(add_day_dateutil_relativedelta, 'relativedelta'), (add_day_datetime_timedelta, 'timedelta'), (add_day_datetime_timedelta_conversion, 'timedelta+conversion'), (add_day, 'timedelta+conversion+dst')] print(': 5> 5>'.format('Method', 'Samoa', 'DST')) for method, name in to_test: print(': 5> 5>' .format(name, test_samoa(method), test_dst(method))) 

Test results

Method : Samoa DST relativedelta : 0 0 timedelta : 0 0 timedelta+conversion : 1 0 timedelta+conversion+dst : 1 1 

Источник

Python add one day to date

Last updated: Feb 18, 2023
Reading time · 4 min

banner

# Table of Contents

# Add days to a date in Python

Use the timedelta() class from the datetime module to add days to a date.

The timedelta class can be passed a days argument and adds the specified number of days to the date.

Copied!
from datetime import datetime, date, timedelta my_str = '09-24-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-24 00:00:00 # ✅ Add 3 days to a date result = date_1 + timedelta(days=3) print(result) # 👉️ 2023-09-27 00:00:00

add days to date

Make sure to import the datetime or date and timedelta classes from the datetime module.

The example uses the datetime.strptime() method to get a datetime object that corresponds to the provided date string, parsed according to the specified format.

Читайте также:  String to html color

Once we have the datetime object, we can use the timedelta class to add days to it.

Copied!
from datetime import datetime, timedelta my_str = '09-24-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-24 00:00:00 result = date_1 + timedelta(days=3) print(result) # 👉️ 2023-09-27 00:00:00

The date string in the example is formatted as mm-dd-yyyy .

If you have a date string that is formatted in a different way, use this table of the docs to look up the format codes you should pass as the second argument to the strptime() method.

# Adding days to the current date

If you need to add days to the current date, use the datetime.today() method.

Copied!
from datetime import datetime, timedelta current_date = datetime.today() print(current_date) # 👉️ 2023-07-22 10:43:15.536277 # ✅ Add 7 days to the current date result = current_date + timedelta(days=7) print(result) # 👉️ 2023-07-29 10:43:15.536277

adding days to current date

The datetime.today() method returns the current local datetime .

# Using the date class to add days to a date

You can also use the date() class instead of the datetime class when adding days to a date.

Copied!
from datetime import date, timedelta date_1 = date(2023, 9, 24) print(date_1) # 👉️ 2023-09-24 reuslt = date_1 + timedelta(days=3) print(reuslt) # 👉️ 2023-09-27

using date class to add days to date

The datetime.timedelta class can be passed the days we want to add to the date or datetime objects.

The timedelta class can be passed the days , weeks , hours , minutes , seconds , milliseconds and microseconds as arguments.

All of the arguments are optional and default to 0 .

It's best to only use keyword arguments in a call to the timedelta class as the order of arguments can be confusing.

# Using the date() method to get the date after the operation

If you only need to extract the date after the operation, call the date() method on the datetime object.

Copied!
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2023-02-18 18:41:00.827570 result = now + timedelta(days=5) print(result) # 👉️ 2023-02-23 18:41:00.827570 print(result.date()) # 👉️ 2023-02-23

The datetime.date method returns a date object with the same year, month and day.

If you need to format the date in a certain way, use a formatted string literal.

Copied!
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2023-02-18 18:41:30.558332 result = now + timedelta(days=6) print(result) # 👉️ 2023-02-24 18:41:30.558332 print(result.date()) # 👉️ 2023-02-24 print(f'result:%Y-%m-%d %H:%M:%S>') # 👉️ 2023-02-24 18:41:30

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Make sure to wrap expressions in curly braces - .

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

# Adding days to a date object that stores the current date

Here is an example of adding days to a date object that represents the current date.

Copied!
from datetime import date, timedelta date_1 = date.today() print(date_1) # 👉️ 2023-07-22 result = date_1 + timedelta(days=7) print(result) # 👉️ 2023-07-29

adding days to date object that stores current date

The date.today method returns a date object that represents the current local date.

# Add weeks to a date in Python

Use the timedelta() class from the datetime module to add weeks to a date.

The timedelta class can be passed a weeks argument and adds the specified number of weeks to the date.

Copied!
from datetime import datetime, date, timedelta my_str = '09-14-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-14 00:00:00 # ✅ add 2 weeks to a date result = date_1 + timedelta(weeks=2) print(result) # 👉️ 2023-09-28 00:00:00

Make sure to import the datetime or date and timedelta classes from the datetime module.

We passed the weeks keyword argument to the timedelta class, but you can also pass it a days argument, e.g. timedelta(days=14) .

Either way, the month (and year) will roll over if necessary.

The example uses the datetime.strptime() method to get a datetime object that corresponds to the provided date string, parsed according to the specified format.

Once we have the datetime object, we can use the timedelta class to add weeks to it.

Copied!
from datetime import datetime, date, timedelta my_str = '09-14-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-14 00:00:00 result = date_1 + timedelta(weeks=2) print(result) # 👉️ 2023-09-28 00:00:00

The date string in the example is formatted as mm-dd-yyyy .

If you have a date string that is formatted in a different way, use this table of the docs to look up the format codes you should pass as the second argument to the strptime() method.

# Adding weeks to the current date

If you need to add weeks to the current date, use the datetime.today() method.

Copied!
from datetime import datetime, timedelta current_date = datetime.today() print(current_date) # 👉️ 2023-02-18 18:46:07.541963 result = current_date + timedelta(weeks=1) print(result) # 👉️ 2023-02-25 18:46:07.541963

The datetime.today() method returns the current local datetime.

# Using the date() class to add weeks to a date

You can also use the date() class instead of the datetime class when adding weeks to a date.

Copied!
from datetime import date, timedelta date_1 = date(2023, 9, 7) print(date_1) # 👉️ 2023-09-07 result = date_1 + timedelta(weeks=3) print(result) # 👉️ 2023-09-28

The datetime.timedelta class can be passed the weeks we want to add to the date or datetime objects.

# Adding weeks to a date object that stores the current date

The following example adds weeks to a date object that represents the current date.

Copied!
from datetime import date, timedelta date_1 = date.today() print(date_1) # 👉️ 2023-02-18 result = date_1 + timedelta(weeks=2) print(result) # 👉️ 2023-03-04

The date.today method returns a date object that represents the current local date.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью