Last modified: Nov 16, 2025 By Alexander Williams
Excel Dates Times Python openpyxl Guide
Working with dates and times in Excel using Python openpyxl is essential. Many data automation tasks involve temporal data. This guide covers everything you need.
Understanding Excel Date and Time Storage
Excel stores dates as serial numbers. The integer part represents days since January 1, 1900. The decimal part represents time as a fraction of a day.
For example, 45000.5 represents June 5, 2023 at 12:00 PM. Understanding this system helps you manipulate dates programmatically.
Basic Date and Time Operations
Let's start with basic date operations. You can write dates directly to cells. The datetime module provides the necessary classes.
from openpyxl import Workbook
from datetime import datetime, date, time
# Create workbook and select active sheet
wb = Workbook()
ws = wb.active
# Write current date and time
ws['A1'] = datetime.now()
ws['A2'] = date(2023, 12, 25)
ws['A3'] = time(14, 30, 45)
# Save the workbook
wb.save('basic_dates.xlsx')
This code creates dates and times in Excel. The current datetime goes in A1. Christmas 2023 goes in A2. 2:30:45 PM goes in A3.
Formatting Dates and Times
Raw dates appear as serial numbers. You need proper formatting. Use number formats to display dates correctly.
Apply formats using the number_format property. Excel recognizes standard date format codes. This makes dates human-readable.
from openpyxl.styles import numbers
# Apply different date formats
ws['B1'].number_format = 'YYYY-MM-DD'
ws['B2'].number_format = 'DD/MM/YYYY HH:MM:SS'
ws['B3'].number_format = 'MMM D, YYYY'
# Copy dates from column A
ws['B1'] = ws['A1'].value
ws['B2'] = ws['A1'].value
ws['B3'] = ws['A2'].value
wb.save('formatted_dates.xlsx')
Column B now shows formatted dates. B1 uses ISO format. B2 shows full datetime. B3 uses abbreviated month format.
For more complex formatting needs, check our Advanced Number Formatting Python openpyxl Guide.
Date Calculations and Operations
You can perform calculations with dates. Add days to a date. Calculate differences between dates. This is useful for scheduling and tracking.
from datetime import timedelta
# Date calculations
start_date = date(2023, 1, 1)
ws['C1'] = start_date
ws['C1'].number_format = 'YYYY-MM-DD'
# Add 30 days
end_date = start_date + timedelta(days=30)
ws['C2'] = end_date
ws['C2'].number_format = 'YYYY-MM-DD'
# Calculate difference in days
date_diff = (end_date - start_date).days
ws['C3'] = date_diff
ws['C3'].number_format = '0'
wb.save('date_calculations.xlsx')
This demonstrates basic date arithmetic. C1 shows start date. C2 shows date after 30 days. C3 shows the difference as days.
Working with Time Zones
Time zones add complexity to datetime handling. Always be aware of timezone context. Use aware datetime objects for accuracy.
from datetime import timezone, timedelta
# Create timezone-aware datetime
utc_time = datetime(2023, 6, 15, 10, 0, 0, tzinfo=timezone.utc)
est_time = utc_time.astimezone(timezone(timedelta(hours=-5)))
ws['D1'] = utc_time
ws['D2'] = est_time
# Apply consistent format
for cell in ws['D1:D2']:
cell[0].number_format = 'YYYY-MM-DD HH:MM:SS'
wb.save('timezone_dates.xlsx')
D1 shows UTC time. D2 shows equivalent Eastern Time. This ensures proper timezone handling in your applications.
Parsing and Converting Dates
You often need to convert string dates to datetime objects. Use datetime.strptime() for parsing. Handle various date string formats.
# Parse date strings
date_strings = ['2023-12-25', '25/12/2023', 'Dec 25, 2023']
date_formats = ['%Y-%m-%d', '%d/%m/%Y', '%b %d, %Y']
for i, (date_str, fmt) in enumerate(zip(date_strings, date_formats)):
parsed_date = datetime.strptime(date_str, fmt)
ws[f'E{i+1}'] = parsed_date
ws[f'E{i+1}'].number_format = 'YYYY-MM-DD'
wb.save('parsed_dates.xlsx')
This code parses different date string formats. Each format requires the correct format string. The result is standardized dates in Excel.
Working with Excel Date Functions
Excel has built-in date functions. You can write these formulas using openpyxl. This leverages Excel's calculation engine.
# Write Excel date formulas
ws['F1'] = '=TODAY()'
ws['F2'] = '=NOW()'
ws['F3'] = '=DATE(2023,12,25)'
ws['F4'] = '=DATEDIF(DATE(2023,1,1),DATE(2023,12,31),"D")'
wb.save('excel_date_functions.xlsx')
F1 shows current date. F2 shows current datetime. F3 creates a specific date. F4 calculates days between dates.
Handling Date Ranges and Series
Creating date ranges is common in reporting. Generate sequences of dates automatically. Use Python's date arithmetic for this.
# Generate date range
start = date(2023, 1, 1)
date_range = [start + timedelta(days=x) for x in range(7)]
for i, dt in enumerate(date_range):
ws[f'G{i+1}'] = dt
ws[f'G{i+1}'].number_format = 'DDD, MMM D'
wb.save('date_ranges.xlsx')
This creates a week of dates starting January 1, 2023. Each date shows day name and date. Useful for weekly reports and schedules.
Best Practices for Date Handling
Follow these best practices for reliable date operations. Always use consistent timezone handling. Validate date inputs before processing.
Use descriptive variable names for dates. Document date format assumptions. Test with edge cases like leap years.
For large datasets, consider using our Python openpyxl Streaming Write Mode Guide for better performance.
Common Date and Time Issues
Watch out for these common problems. Excel's 1900 date system has known issues. February 29, 1900 doesn't exist but Excel accepts it.
Time zone conversions can cause off-by-one errors. Daylight saving time changes require special handling. Always test with historical date changes.
When working with multiple sheets, our Copy Move Delete Sheets Python openpyxl Guide can help manage date data across worksheets.
Conclusion
Mastering dates and times in Excel with Python openpyxl is crucial for data automation. You learned basic operations, formatting, calculations, and timezone handling.
Remember to always format dates for readability. Use timezone-aware objects when needed. Leverage Excel formulas when appropriate.
With these techniques, you can handle any date-related task in your Excel automation projects. Practice with different date scenarios to build confidence.