Python timedelta days to int

Как извлечь дни как целые числа из объекта timedelta64 [ns] в Python

Это должно преобразовать ваш тип timedelta64[ns] в float64 , представляющий дни:

data['difference'].astype('timedelta64[D]') 

Этот метод astype(‘timedelta64[D]’) (около 96 мс) намного эффективнее, чем dt.days. (около 24 с) для 4 000 000 строк.

Вы можете использовать dt.days для извлечения всего нескольких дней из своей серии,

df.difference Out[117]: 0 -1 days +00:00:05 1 NaT 2 -1 days +00:00:05 3 1 days 00:00:00 dtype: timedelta64[ns] df.difference.dt.days Out[118]: 0 -1 1 NaN 2 -1 3 1 dtype: float64 
dr Out[93]: 0 -1 days +00:00:05 1 NaT 2 1 days 02:04:05 3 1 days 00:00:00 dtype: timedelta64[ns] dr.dt.components Out[95]: days hours minutes seconds milliseconds microseconds nanoseconds 0 -1 0 0 5 0 0 0 1 NaN NaN NaN NaN NaN NaN NaN 2 1 2 4 5 0 0 0 3 1 0 0 0 0 0 0 

Этот метод довольно медленный. Напротив, метод astype(‘timedelta64[D]’) (около 96 мс) намного эффективнее, чем dt.days. (около 24 с) для 4 000 000 строк.

Если вы можете получить вывод в виде строки, python re должен помочь.

''.join(item[0]+',' for item in re.findall('8+ days', output))[:-1] 

Ещё вопросы

  • 1 hibernate 4 и joda-LocalDate и сохраните его как дату SQL
  • 1 Диалог отклонить по кнопке да
  • 0 li.hover не меняет цвет
  • 0 Сделайте верхнюю и нижнюю границу divs неровным краем
  • 0 AngularJS — как передать объект (созданный на лету) с интерполированными данными в пользовательскую директиву
  • 1 Передача примитивного Типа в качестве параметра из XAML
  • 0 Gmail SMTP с использованием CodeIgniter
  • 0 Привязка события jquery ко всем текстовым элементам в div
  • 0 Наименование Conseqences в браузере
  • 1 EntityFramework — Как заполнить дочерние элементы?
  • 1 Ошибка: невозможно получить доступ к jarfile sailfin-installer-v1-b60g-linux.jar
  • 1 Измените цвет отдельных ящиков на участках с пандой
  • 1 Динамический запрос crm rest builder для отношения многих ко многим
  • 0 Исправление синтаксической ошибки переменной селектора jQuery
  • 0 Неверно сформированный URL передан фабрике angularjs
  • 0 Apache скинул 404 для файла в папке var / www
  • 1 Как я могу определить базовый тип в объектном типе dtype?
  • 0 как перетащить div в другой div и после перетаскивания div не двигайтесь с помощью jQuery
  • 0 Разрешить службе взаимодействовать с рабочим столом — Служба Windows взаимодействует с сервером OPC
  • 1 Настройки парсера DOM, чтобы избежать атаки XML Injection
  • 1 Начальные проблемы с перекрашиванием и подсчет соседних проблем
  • 1 TargetInvocationException при запуске проекта на wp7
  • 0 Поведение CodeIgniter, конструкторы и маршруты
  • 0 Php — вызов неопределенной функции mssql_query ()
  • 1 NullPointException и длина массива объектов
  • 1 Специальный символ Python YAML и несколько строк
  • 0 LinkedStack и его шаблонный класс
  • 0 Извлечение JSON в транспортир и сравнение его с данными, отправленными из серверной части
  • 1 Хеширование в Java отрицательных чисел
  • 0 Создание угловой директивы для повторного использования кода — ошибка синтаксического анализа при создании HTML
  • 1 GoogleSignInClient.signOut вылетает с: «Вызовите connect () и дождитесь вызова onConnected ()»
  • 0 C ++ VS2010 с использованием параллелизма пространства имен; Нет пространства имен с этим именем
  • 1 Как задать путь для корректной работы плагина gulp-deporder в скриптах?
  • 1 WCF замедляется с несколькими запросами
  • 1 Установка значения из одного класса в другой в Java
  • 0 результат связывания двух сильных функциональных символов с одинаковой сигнатурой функции использует g ++ и почему?
  • 1 Какова цель программирования для интерфейса? [Дубликат]
  • 1 Как удалить тень из панели приложений и добавить тень в TabLayout
  • 0 Как я могу сгенерировать необычный формат JSON с помощью PHP
  • 0 Неожиданные результаты с преобразованием строк wchar_t и c_str
  • 1 Поворот экрана с помощью ViewPager — проблема с FragmentManager и FragmentPagerAdapter
  • 0 Оператор удаления MySQLi не удаляет
  • 0 определение статической функции в заголовке
  • 1 Чистый способ остановить RMI сервер
  • 0 Получение углового контроллера через $ scope в модульном тесте
  • 0 Моделирование при возврате тега выбора равно нулю / не определено
  • 0 Преобразование координат SVG в координаты карты изображения HTML
  • 0 Почему SetInterval не работает (работает только один раз)
  • 1 Почему нажатие кнопки работает только в IE
  • 1 Чтение геометрии Postgres в байт [] с помощью спящего режима?
Читайте также:  Css transform scale animation

Источник

Convert timedelta to Integer in Python (Example)

TikTok Icon Statistics Globe

In this Python tutorial, you’ll learn how to convert a timedelta object to an integer.

Here’s the step-by-step process!

Example Data & Imported Modules

import datetime # Loading datetime module

We’ll also define a timedelta object that we can use in the following examples:

td = datetime.timedelta(days=56, seconds=62700, microseconds=479001) # sample timedelta generation print(td) # printing the sample timedelta # 56 days, 17:25:00.479001

Example 1: Converting timedelta to Integer

To change the timedelta object to an integer, first, we can convert it to seconds and store the result as an integer. You can think of it as a timestamp.

td_in_sec = td.total_seconds() # getting the total amount of time in seconds print(td_in_sec) # printing total_seconds # 4901100.479001

If the timedelta has a non-zero microsecond component, then we can simply convert the float number to an integer. If this is not the case, first, we should multiply the number by a million to include the decimal part in the integer part.

td_in_sec = td_in_sec * 1000000 # Combining the decimal part to the integer part int_td = int(td_in_sec) # Converting the number to an integer print(int_td) # printing the integer # 4901100479001

Transforming Integer to timedelta Back

If we want to transform an integer to a timedelta object back, then we need to do the operations in reverse order. See the following.

td_in_sec = int_td / 1000000 # Getting the time amount in seconds again td_reverse = datetime.timedelta(seconds=td_in_sec) # re-creating the timedelta print(td_reverse) # printing the re-created timedelta # 56 days, 17:25:00.479001

Video & Further Resources

If you need further explanations on the Python code of this tutorial, I can recommend having a look at the following video on my YouTube channel. In the video, I illustrate the Python programming code of this article in Python:

Читайте также:  Поэлементное сложение матриц python

The YouTube video will be added soon.

In addition, you might want to read the related articles on my homepage. Some posts can be found below:

You have learned in this tutorial how to transform timedelta to integer in Python programming. Please let me know in the comments section, in case you have any further questions or comments.

Ömer Ekiz Python Programming & Informatics

This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get further information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.

Источник

How to convert a timedelta object to int in Pandas and Python?

EasyTweaks.com

Use the dt.days property of the pandas library timedelta object to convert your timedeltas to days, hours, or minutes – all int64 objects. Here is a simple code snippet to use:

my-df[my_td_column] = my-df[my_td_column].dt.days #for hours my-df[my_td_column] = my-df[my_td_column].dt.days*24 # for minutes: my-df[my_td_column] = my-df[my_td_column].dt.days*24*60 

Create example data

We will start by creating some data that you can definitely use in order to follow along with this tutorial.

import pandas as pd install_date = pd.Series(pd.date_range(start='1/1/25', periods = 5, freq='B')) first_failure_date = pd.to_datetime(pd.Series( ['2026-02-24', '2025-03-15', '2025-10-11', '2026-08-12', '2026-10-23'])) # Create a dataframe performance = pd.DataFrame(dict(install_date = install_date, first_failure_date = first_failure_date)) #Read the dataframe first rows performance.head()
install_date first_failure_date
0 2025-01-01 2026-02-24
1 2025-01-02 2025-03-15
2 2025-01-03 2025-10-11
3 2025-01-06 2026-08-12
4 2025-01-07 2026-10-23

Let’s look at the data types in our DataFrame:

install_date datetime64[ns] first_failure_date datetime64[ns] dtype: object

Calculate the timedelta column

Using a vectorized operation, we will calculate a “time for first failure” column, by subtracting the two timestamp / datetime columns.

 performance ['time_to_first_failure'] = performance ['first_failure_date'] - performance['install_date'] performance.head()

Looking our DataFrame we see a new column:

install_date first_failure_date time_to_first_failure
0 2025-01-01 2026-02-24 419 days
1 2025-01-02 2025-03-15 72 days
2 2025-01-03 2025-10-11 281 days
3 2025-01-06 2026-08-12 583 days
4 2025-01-07 2026-10-23 654 days
install_date datetime64[ns] first_failure_date datetime64[ns] time_to_first_failure timedelta64[ns] dtype: object

Convert timedelta objects to integers

We would like to convert the last column in our pandas DataFrame from time delta to int object types. If we try to use astype() to convert the timedelta to int32, Python will render an exception:

# will render a type error performance['time_first_failure'].astype('int32')

The following error will be displayed:

TypeError: cannot astype a datetimelike from [timedelta64[ns]] to [int32]

Cast a timedelta object to a datetime

Converting a timedelta to datetime makes little sense, and will render the following error message:

TypeError: dtype timedelta64[ns] cannot be converted to datetime64[ns]

Most probably you might want to add or subtract a timedelta from a date.

performance['install_date'] = performance['first_failure_date'] - performance['time_to_first_failure']

Convert timedelta to days

We use the dt accesor of your timedelta series object to return the number of days (will be returned as an int64 data type):

performance['time_to_first_failure'] = performance['time_to_first_failure'].dt.days

Convert timedelta to months (integer values)

(performance['time_to_first_failure'].dt.days/30).astype('int64')

Cast timedelta to float numbers

Let’s use the conversion to months as an example on how to turn timedelta to floats:

round(performance['time_to_first_failure'].dt.days/30, 2)

This will return the following Series of floats / decimals:

0 13.97 1 2.40 2 9.37 3 19.43 4 21.80 Name: time_to_first_failure, dtype: float64

Источник

Читайте также:  Java localdate to zoneddatetime

Convert Timedelta to Int in Pandas

Convert Timedelta to Int in Pandas

This tutorial will discuss converting the timedelta to int using the dt attribute in Pandas.

Convert the timedelta to int Using the dt Attribute in Pandas

To convert the timedelta to an integer value, we can use the pandas library’s dt attribute. The dt attribute allows us to extract components of the timedelta . For example, we can extract the year, month, day, minutes, or seconds using the dt attribute. To do that, we need to write the component’s name after the dt attribute. To show all the components of the timedelta variable, we can use the components attribute. For example, let’s create a time series using the pandas Series attribute and show its components using the components attribute.

import pandas as pd time_series = pd.Series(pd.timedelta_range(start='1 days', end='10 days', freq='1500T')) time_series.dt.components 

Pandas time series

As you can see, the components attribute showed all the components of the time series. The timedelta_range() attribute is used in the above code to create the time series. We can define the starting and ending point and the frequency at which the time will change inside the timedelta_range() attribute. We can extract any of these components using the name of that component. For example, let’s extract the days component from the above time series. See the code below.

import pandas as pd time_series = pd.Series(pd.timedelta_range(start='1 days', end='10 days', freq='1500T')) time_series.dt.days 
0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 dtype: int64 

You can extract any component you want from the above time series. We can also convert the timedelta to an integer by dividing it by the timedelta of one day or by extracting its integer part using the astype() attribute. For example, let’s create a timedelta object and convert it into an integer to get the value of the day using NumPy . See the code below.

import numpy as np x = np.timedelta64(2058311000000000, 'ns') day = x.astype('timedelta64[D]') days.astype(int) 

The timedelta is actually in the int64 data type, and we can extract our desired component by converting it into an int using the astype() attribute. We can also convert the timedelta to hours or seconds or any other component using the same method. To do that, we need to change D in the third line of code to h for hours and s for seconds, and so on.

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Related Article — Pandas DateTime

Источник

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