Keywords: Excel | Date Conversion | Number Formatting | DATEVALUE
Abstract: This article explains how Excel converts dates to numbers, covering the underlying system, the use of General format, and the DATEVALUE function. It also discusses Excel's date system errors and provides code examples for understanding the conversion.
In Microsoft Excel, dates are stored as serial numbers representing the number of days since January 1, 1900. This system allows for easy date arithmetic and conversion.
Excel Date System
Excel internally saves dates as numbers. For example, the date 10/26/2013 corresponds to the number 41573. This number is calculated as the days elapsed from a base date.
Converting Dates in Excel
To view the underlying number of a date, change the cell format to General. This will display the serial number. If the date is stored as text, use the DATEVALUE function to convert it to a number.
Excel's Date System Errors
Excel incorrectly treats 1900 as a leap year, which affects dates before March 1, 1900. The actual base date is December 30, 1899, to account for this error.
Code Example
To understand the conversion, here is a Python function that mimics Excel's date-to-number calculation:
import datetime
def excel_date_number(date_str):
# Parse the date string in format MM/DD/YYYY
date_obj = datetime.datetime.strptime(date_str, "%m/%d/%Y").date()
base_date = datetime.date(1899, 12, 30)
days_diff = (date_obj - base_date).days
# Adjust for Excel's error for dates before 1900-03-01
if date_obj < datetime.date(1900, 3, 1):
days_diff -= 1
return days_diff
# Example usage
print(excel_date_number("10/26/2013")) # Should output 41573This code demonstrates the logic behind Excel's date conversion, helping users understand the formula.