Home  >  Article  >  Backend Development  >  How to Convert Excel-Style Floating-Point Dates to Pandas Datetime Objects?

How to Convert Excel-Style Floating-Point Dates to Pandas Datetime Objects?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 12:57:10782browse

How to Convert Excel-Style Floating-Point Dates to Pandas Datetime Objects?

Converting Excel-Style Dates with Pandas

When parsing dates from Excel files, you may encounter dates represented as floating-point numbers, such as 42580.3333333333. Pandas provides a convenient way to convert these Excel dates into regular datetime objects.

To do this, you can create a TimedeltaIndex from the Excel date numbers, adding the scalar datetime for 1900,1,1 to the index. This will convert the Excel dates to the corresponding datetime objects:

import pandas as pd
df = pd.DataFrame({'date': [42580.3333333333, 10023]})
df['real_date'] = pd.TimedeltaIndex(df['date'], unit='d') + pd.datetime(1900, 1, 1)

However, it's important to note that Excel uses a different date system than Pandas, with the epoch being December 30, 1899, instead of January 1, 1900. To account for this, you may need to adjust the starting date:

df['real_date'] = pd.TimedeltaIndex(df['date'], unit='d') + pd.datetime(1899, 12, 30)

The above is the detailed content of How to Convert Excel-Style Floating-Point Dates to Pandas Datetime Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn