parse pands.datetime to days and hours in python

To parse a Pandas datetime column into days and hours in Python, you can use the dt accessor in Pandas along with the days and seconds attributes of the timedelta object.

Here's an example code snippet:

main.py
import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'datetime_column': ['2022-01-01 10:30:00', '2022-01-02 12:45:00', '2022-01-03 08:15:00']})

# Convert the column to datetime type
df['datetime_column'] = pd.to_datetime(df['datetime_column'])

# Calculate days and hours from the datetime column
df['days'] = df['datetime_column'].dt.days
df['hours'] = df['datetime_column'].dt.seconds // 3600

# Display the modified DataFrame
print(df)
455 chars
15 lines

This will output the DataFrame with two additional columns - days and hours, which represent the number of days and hours respectively, parsed from the datetime_column.

Note: The dt.days attribute returns the number of days as a positive or negative integer, while the dt.seconds attribute returns the total number of seconds of the datetime value. Therefore, we divide it by 3600 to get the number of hours.

Remember to import the pandas library before using these functions.

related categories

gistlibby LogSnag