How does division by np.timedelta64 work?

Viewed 24

I have a piece of code doing those calculations :

import numpy as np
import pandas as pd

a = pd.Timestamp(2022, 1, 1)
b = pd.Timestamp(2022, 7, 1)

x = (b - a) / np.timedelta64(1, "M")  # duration in months
y = (b - a) / np.timedelta64(1, "Y")  # duration in years

x and y values are 5.9467... and 0.4955..., which is correct (almost 6 months and a half year).

Can someone know by which float number the division is done ?

For example, for months, it could be dividing by 365/12, but it is not the case.

1 Answers

It looks like it is:

# month
Timedelta('30 days 10:29:06')

and:

# year
Timedelta('365 days 05:49:12')

Which corresponds to the real duration of a Year (365.2425 days).

You can cheat for the conversion using:

a+np.timedelta64(1, "M")-a

and:

a+np.timedelta64(1, "Y")-a

ratio: 12

m = a+np.timedelta64(1, "M")-a
y = a+np.timedelta64(1, "Y")-a
y/m # 12
Related