how to convert dateutil.relativedelta object to datetime.timedelta object?

  • Last Update :
  • Techknowledgy :

In case someone is looking to convert a relativedelta to a timedelta from a specific date, simply add and subtract the known time:

utcnow = datetime.utcnow()
rel_delta = relativedelta(months = -2)
time_delta = utcnow + rel_delta - utcnow # e.g, datetime.timedelta(days = -62)

Depending on why you want to call total_seconds, it may be possible to refactor your code to avoid the conversion altogether. For example, consider a check on whether or not a user is over 18 years old:

datetime.date.today() - user['dateOfBirth'] < datetime.timedelta(days = 365 * 18)

This check is not a good idea, because the timedelta object does not account for things like leap years. It's tempting to rewrite as:

datetime.date.today() - user['dateOfBirth'] < dateutil.relativedelta.relativedelta(years = 18)

which would require comparing a timedelta (LHS) to a relativedelta (RHS), or converting one to the other. However, you can refactor the check to avoid this conversion altogether:

user['dateOfBirth'] + dateutil.relativedelta.relativedelta(years = 18) > datetime.date.today()

Suggestion : 2

The relativedelta type is designed to be applied to an existing datetime and can replace specific components of that datetime, or represents an interval of time.,There are two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes:,The order of attributes considered when this relativedelta is added to a datetime is:,Here is another example using an absolute relativedelta. Notice the use of year and month (both singular) which causes the values to be replaced in the original datetime rather than performing an arithmetic operation on them.

relativedelta(datetime1, datetime2)
relativedelta(arg1 = x, arg2 = y, arg3 = z...)

year, month, day, hour, minute, second, microsecond:
   Absolute information(argument is singular);
adding or subtracting a
relativedelta with absolute information does not perform an arithmetic
operation, but rather REPLACES the corresponding value in the
original datetime with the value(s) in relativedelta.

years, months, weeks, days, hours, minutes, seconds, microseconds:
   Relative information, may be negative(argument is plural);
adding
or subtracting a relativedelta with relative information performs
the corresponding arithmetic operation on the original datetime value
with the information in the relativedelta.

weekday:
   One of the weekday instances(MO, TU, etc) available in the
relativedelta module.These instances may receive a parameter N,
   specifying the Nth weekday, which could be positive or negative(like MO(+1) or MO(-2)).Not specifying it is the same as specifying +
   1. You can also use an integer, where 0 = MO.This argument is always
relative e.g.if the calculated date is already Monday, using MO(1)
or MO(-1) won 't change the day. To effectively make it absolute, use
it in combination with the day argument(e.g.day = 1, MO(1) for first Monday of the month).

leapdays:
   Will add given days to the date found,
   if year is a leap
year, and the date found is post 28 of february.

yearday, nlyearday:
   Set the yearday or the non - leap year day(jump leap days).
These are converted to day / month / leapdays information.
>>> from datetime
import datetime
   >>>
   from dateutil.relativedelta
import relativedelta, MO
   >>>
   dt = datetime(2018, 4, 9, 13, 37, 0) >>>
   delta = relativedelta(hours = 25, day = 1, weekday = MO(1)) >>>
   dt + delta
datetime.datetime(2018, 4, 2, 14, 37)
>>> relativedelta(days = 1.5, hours = 2).normalized()
relativedelta(days = +1, hours = +14)
>>> from datetime
import * ;
from dateutil.relativedelta
import *
>>>
import calendar
   >>>
   NOW = datetime(2003, 9, 17, 20, 54, 47, 282310) >>>
   TODAY = date(2003, 9, 17)
>>> from datetime
import * ;
from dateutil.relativedelta
import *
>>>
import calendar

Suggestion : 3

Step 2: Create an object of timedelta, to represent an interval of N minutes. For that, pass the argument minutes with value N in the timedelta constructor.,So, to add minutes to a given timestamp, we can create a relativedelta object to represents the interval in minutes and then add it to the datetime object containing give date. Let’s understand with an example,,Step 3: Add the timedelta object to the datetime object created in step 1. It will give us a new datetime object, pointing to a new timestamp i.e. N minutes after the given timestamp.,We created a DateOffset object by passing minutes argument as 3. Then added that to the datetime object. It returned a new datetime object pointing to a different timestamp i.e. after 3 minutes from the given timestamp.

Add 15 minutes to a timestamp in python

from datetime
import datetime
from datetime
import timedelta

# Given timestamp in string
time_str = '23/2/2020 11:12:22.234513'
date_format_str = '%d/%m/%Y %H:%M:%S.%f'

# create datetime object from timestamp string
given_time = datetime.strptime(time_str, date_format_str)

print('Given timestamp: ', given_time)

n = 15
# Add 15 minutes to datetime object
final_time = given_time + timedelta(minutes = n)

print('Final Time (15 minutes after given time ): ', final_time)

# Convert datetime object to string in specific format
final_time_str = final_time.strftime('%d/%m/%Y %H:%M:%S.%f')
print('Final Time as string object: ', final_time_str)

Output

Given timestamp: 2020 - 02 - 23 11: 12: 22.234513
Final Time(15 minutes after given time): 2020 - 02 - 23 11: 27: 22.234513
Final Time as string object: 23 / 02 / 2020 11: 27: 22.234513

Add 3 minutes to a datetime in python

from datetime
import datetime
import pandas as pd

# Given timestamp in string
time_str = '23/2/2020 11:12:22.234513'
date_format_str = '%d/%m/%Y %H:%M:%S.%f'

# create datetime object from timestamp string
given_time = datetime.strptime(time_str, date_format_str)

print('Given timestamp: ', given_time)

n = 3
# Add 3 minutes to datetime object
final_time = given_time + pd.DateOffset(minutes = n)

print('Final Time (3 minutes after given time ): ', final_time)

# Convert datetime object to string in specific format
final_time_str = final_time.strftime('%d/%m/%Y %H:%M:%S.%f')
print('Final Time as string object: ', final_time_str)

Suggestion : 4

Last Updated : 03 Jun, 2022

Output:

old date is: 2022 - 04
new date is: 2022 - 09

Suggestion : 5

Python Python Home date Samples String List Math Functions Built in Functions File Handling Error Handling Class Object Tkinter Numpy Pandas Python & MySQL SQLite

Importing datetime library

from dateutil.relativedelta
import relativedelta

Watch difference between day and days

# day and days
from dateutil.relativedelta
import relativedelta
from datetime
import date
dt = date.today() # today is 2019 - 09 - 23
# Adding one day to today
print(dt + relativedelta(days = 1)) # 2019 - 09 - 24
# 1 st day of the month
print(dt + relativedelta(day = 1)) # 2019 - 09 - 01
relativedelta(year, month, day, hour, minute, second, microsecond)
relativedelta(year=2021, month=1, day=1, hour=23, minute=56, second=57, microsecond=324534)
2021 1 1 23 56 57 324534
from dateutil.relativedelta
import relativedelta
dt = relativedelta(years = 1, months = 2, days = 3, hours = 23, minutes = 56, seconds = 57, microseconds = 324534)
from datetime
import date
dt_today = date.today() # today is 2019 - 09 - 23
print(dt_today + dt)
2020-11-26 23:56:57.324534
from dateutil.relativedelta
import relativedelta
dt = relativedelta(years = 1, months = 2, days = 3, hours = 23, minutes = 56, seconds = 57, microseconds = 324534)
from datetime
import datetime
dt_now = datetime.now()
print(dt_now)
print(dt_now + dt)

Suggestion : 6

Let us start by importing the datetime module into our Python environment and defining two variables: a date and a timedelta.,What if we would like to sum months to a specific date? The timedelta method, supports calculation of time differences up to week granularity. Hence, in order to calculate time deltas in months or years we should use the relativedelta function.,In the same fashion, we are able to add hours to a Python datetime object. Let’s now calculate the expected takeoff time of our flight.,Today we will learn how to quickly add different time periods to date objects using the Python programming language.

Let us start by importing the datetime module into our Python environment and defining two variables: a date and a timedelta.

import datetime

# define a datetime
sign_date = datetime.date(2022, 6, 7)

#define a timedelta representing the employee notice
notice_interval = datetime.timedelta(days = 60)

Now we’ll go ahead and sum those together, note the usage of the str function that casts the date object so that we can concatenate it into the print statement:

expected_start = sign_date + notice_interval

print('The expected start day of this employee is: ' + str(expected_start))

We’ll get the following result:

The expected start of this employee is: 2022 - 08 - 06

Same result as expected:

The expected start of this employee is: 2022 - 08 - 07

In the same fashion, we are able to add hours to a Python datetime object. Let’s now calculate the expected takeoff time of our flight.

arrival_date = datetime.datetime(2002, 7, 8, 10, 35)

layover_lenght = datetime.timedelta(hours = 2)

take_off = arrival_date + layover_lenght

print('The expected takeoff time is: ' + str(
   take_off))