How to Increment a Datetime by One Day

How to increment a datetime by one day?

date = datetime.datetime(2003,8,1,12,4,5)
for i in range(5):
date += datetime.timedelta(days=1)
print(date)

How to increment date in datetime in Python list by one day?

In your approach you should be updating the iterable, not sure what date is there. Here's one approach using a list comprehension and assuming a list of strings (otherwise no need for datetime.strptime):

td = datetime.timedelta(days=1)
l = [datetime.datetime.strptime(i, '%Y-%m-%d %H:%M:%S.%f') + td for i in date_list]

print(l)

[datetime.datetime(2019, 9, 12, 14, 50, 10, 326806),
datetime.datetime(2019, 9, 12, 14, 50, 10, 326806),
datetime.datetime(2019, 9, 12, 14, 50, 10, 326806)]

Is there a simple way to increment a datetime object one month in Python?

Check out from dateutil.relativedelta import *
for adding a specific amount of time to a date, you can continue to use timedelta for the simple stuff i.e.

import datetime
from dateutil.relativedelta import *
use_date = datetime.datetime.now()

use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)

or you can start using relativedelta

use_date = use_date+relativedelta(months=+1)

use_date = use_date+relativedelta(years=+1)

for the last day of next month:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)

Right now this will provide 29/02/2016

for the penultimate day of next month:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)

last Friday of the next month:

use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))

2nd Tuesday of next month:

new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))

As @mrroot5 points out dateutil's rrule functions can be applied, giving you an extra bang for your buck, if you require date occurences.

for example:

Calculating the last day of the month for 9 months from the last day of last month.

Then, calculate the 2nd Tuesday for each of those months.

from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)

#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)

#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
print(ld)

#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
print(tuesday)

Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00

2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00

rrule could be used to find the next date occurring on a particular day.

e.g. the next 1st of January occurring on a Monday (Given today is the 4th November 2021)

from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import *
year = rrule(YEARLY,dtstart=datetime.now(),bymonth=1,bymonthday=1,byweekday=MO)[0].year
year
2024

or the next 5 x 1st of January's occurring on a Monday

years = rrule(YEARLY,dtstart=datetime.now(),bymonth=1,bymonthday=1,byweekday=MO)[0:5]
for i in years:print(i.year)
...
2024
2029
2035
2046
2052

The first Month next Year that starts on a Monday:

>>> month = rrule(YEARLY,dtstart=datetime.date(2023, 1, 1),bymonthday=1,byweekday=MO)[0]
>>> month.strftime('%Y-%m-%d : %B')
'2023-05-01 : May'

If you need the months that start on a Monday between 2 dates:

months = rrule(YEARLY,dtstart=datetime.date(2025, 1, 1),until=datetime.date(2030, 1, 1),bymonthday=1,byweekday=MO)
>>> for m in months:
... print(m.strftime('%Y-%m-%d : %B'))
...
2025-09-01 : September
2025-12-01 : December
2026-06-01 : June
2027-02-01 : February
2027-03-01 : March
2027-11-01 : November
2028-05-01 : May
2029-01-01 : January
2029-10-01 : October

This is by no means an exhaustive list of what is available.
Documentation is available here: https://dateutil.readthedocs.org/en/latest/

How to increment a list of time strings by one day?

I changed the approach a bit.

  • First I convert all the string times to datetimes directly, before entering any loop.

  • The while loop is replaced by a for loop.

  • No secondary list is created because otherwise your third element for example will not take into consideration that you added days to your second element, etc. We modify in place the given list.


from datetime import datetime, timedelta

# Base data converted to datetime before any processing.
time_str = ["23:00", "11:00", "1:00", "5:00", "7:00"]
time_str = [datetime.strptime(x, "%H:%M") for x in time_str]

for n in range(len(time_str) - 1):
early = time_str[n]
later = time_str[n+1]
while later < early:
later += timedelta(days=1) # Add as many days as needed.
time_str[n+1] = later # Store the modified date in the list.

print("\n".join(map(str, time_str)))
# 1900-01-01 23:00:00
# 1900-01-02 11:00:00
# 1900-01-03 01:00:00
# 1900-01-03 05:00:00
# 1900-01-03 07:00:00

Add 1 day to my date in Python

You need the datetime module from the standard library. Load the date string via strptime(), use timedelta to add a day, then use strftime() to dump the date back to a string:

>>> from datetime import datetime, timedelta
>>> s = '2004/03/30'
>>> date = datetime.strptime(s, "%Y/%m/%d")
>>> modified_date = date + timedelta(days=1)
>>> datetime.strftime(modified_date, "%Y/%m/%d")
'2004/03/31'

What is the quickest way to increment date string YYYY-MM-DD in Python?

Pure Python

You can use the datetime module, part of the standard library. There are 3 steps:

  1. Convert string to datetime object via strptime.
  2. Add a day via timedelta.
  3. Convert resulting datetime object back to string via strftime.

Here's a demo:

from datetime import datetime, timedelta

x = '2017-05-15'
res = (datetime.strptime(x, '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d')

print(res)
# 2017-05-16

Pandas

The equivalent steps can be performed using 3rd party Pandas:

x = '2017-05-15'

# choose some combination of below methods
res = (pd.Timestamp(x) + pd.DateOffset(days=1)).strftime('%Y-%m-%d')
res = (pd.to_datetime(x) + pd.Timedelta('1 day')).strftime('%Y-%m-%d')

print(res)
# 2017-05-16

Increment a date by one day with each click of a button

You should store your date in a variable and increment the values from there. As jmcilhinney commented, Labels are meant for display and not for storage

'Declare dt As a field
Dim dt As DateTime

'under the form's load event
dt = DateTime.Parse("Sun, 17-02-2019")
lblDate.Text = dt.ToString("ddd-dd-MM-yyyy")

'Under your Button click event
dt=dt.AddDays(1)
lblDate.Text = dt.ToString("ddd-dd-MM-yyyy")

How can I increment a date by one day in Php?

You can use strtotime.

$your_date = strtotime("1 day", strtotime("2016-08-24"));
$new_date = date("Y-m-d", $your_date);

Hope it will help you.



Related Topics



Leave a reply



Submit