Dates & Times
Python - A Quick Start for existing Programers
3 min read
Published Sep 16 2025, updated Aug 17 2026
Guide Sections
Guide Comments
Python provides the datetime module for working with dates, times, and timestamps. This module has the following objects that you can import:
date- represents a calendar date. Use if you only care about year, month, day.time- represents a time of day. Use if you only care about hour, minute, second.datetime- represents a combined date and time. Use for everything together and arithmetic.timedelta- represents a duration or difference between dates/times. Use for durations and date/time calculations.
Import the objects required:
from datetime import date, time, datetime, timedeltadate object
Creation:
# Create a date using year, month, dayd1 = date(2025, 9, 15)print("Date from year, month, day:", d1)# Get today's dated2 = date.today()print("Today's date:", d2)# Create a date from a timestamp (seconds since epoch)ts = 1694764800 # example timestampd3 = date.fromtimestamp(ts)print("Date from timestamp:", d3)# Create a date from an ISO stringiso_str = "2025-09-15"d4 = date.fromisoformat(iso_str)print("Date from ISO string:", d4)Attributes:
year,month,day
Methods:
today()→ current datefromtimestamp(ts)→ date from Unix timestampweekday()→ 0=Monday … 6=Sundayisoweekday()→ 1=Monday … 7=Sundayisoformat()→ 'YYYY-MM-DD'replace(year=…, month=…, day=…)→ return new date with replaced fieldstimetuple()→ struct_time tuple
Operations:
date1 - date2→timedelta- Comparisons:
<,>,==, etc.
time object
Creation:
# Create a time using hour, minute, second, microsecondt1 = time(14, 30, 45)print("\nTime from h,m,s:", t1)# Create a time with microsecondst2 = time(14, 30, 45, 123456)print("Time with microseconds:", t2)# Replace components of a time objectt3 = t1.replace(hour=16, minute=0)print("Time after replace:", t3)# Get current time as a time objectcurrent_time = datetime.now().time()print("Current time:", current_time)# Get current UTC time as a time objectcurrent_utc_time = datetime.utcnow().time()print("Current UTC time:", current_utc_time)Attributes:
hour,minute,second,microsecond,tzinfo
Methods:
isoformat()→ 'HH:MM:SS.microseconds'replace(hour=…, minute=…, second=…)→ new time with replaced fields
Note: time objects do not support arithmetic (use datetime + timedelta instead).
datetime object
Creation:
# Create datetime using year, month, day, hour, minute, second, microseconddt1 = datetime(2025, 9, 15, 14, 30, 45)print("\nDatetime from components:", dt1)# Current local datetimedt2 = datetime.now()print("Current local datetime:", dt2)# Current UTC datetimedt3 = datetime.utcnow()print("Current UTC datetime:", dt3)# Create datetime from timestampdt4 = datetime.fromtimestamp(ts)print("Datetime from timestamp:", dt4)# Create datetime from ISO stringdt5 = datetime.fromisoformat("2025-09-15T14:30:45")print("Datetime from ISO string:", dt5)# Create datetime from a date and time objectd1 = date(2025, 9, 15)t1 = time(14, 30, 45)dt6 = datetime.combine(d1, t1)print("Datetime from date + time objects:", dt6)# Replace components of datetimedt7 = dt1.replace(year=2026, hour=16)print("Datetime after replace:", dt7)Attributes:
year, month, day, hour, minute, second, microsecond, tzinfo
Methods:
date()→ date parttime()→ time partreplace(...)→ replace componentsisoformat()→ 'YYYY-MM-DDTHH:MM:SS.microseconds'strftime(format)→ formatted stringstrptime(string, format)→ parse string into datetimetimestamp()→ seconds since epoch
Operations:
datetime ± timedelta→ new datetimedatetime1 - datetime2→ timedelta- Comparisons:
<,>,==, etc.
timedelta object
Creation:
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)Attributes:
days,seconds,microseconds
Methods:
total_seconds()→ total duration in seconds
Operations:
datetime + timedelta→ new datetimedatetime - timedelta→ new datetimetimedelta ± timedelta→ new timedelta- Comparisons:
<,>,==, etc.
Formatting output of datetime
The following methods use the codes below:
.strftime()to format a datetime into a string..strptime()with the same codes to parse a string back into datetime.isoformat()is a quick way for standardised output:2025-09-15T14:30:45.
Code | Meaning | Example |
| Year (4 digits) |
|
| Year (2 digits) |
|
| Month (01–12) |
|
| Full month name |
|
| Abbreviated month name |
|
| Day of month (01–31) |
|
| Day of year (001–366) |
|
| Week number of year (Sunday as first day, 00–53) |
|
| Week number of year (Monday as first day, 00–53) |
|
| ISO week number (01–53) |
|
| Full weekday name |
|
| Abbreviated weekday name |
|
| Weekday as number (0=Sunday, 6=Saturday) |
|
| Locale’s date representation |
|
| Hour (00–23) |
|
| Hour (01–12) |
|
| AM/PM |
|
| Minute (00–59) |
|
| Second (00–59) |
|
| Microsecond (000000–999999) |
|
| Locale’s time representation |
|
| Locale’s date and time |
|
| Locale’s date |
|
| Locale’s time |
|
| A literal |
|
Examples:
from datetime import datetime# Get current datetimenow = datetime.now()print("Original datetime object:", now)print("\n# Common formats")# Full date & timeprint("Default ISO:", now.isoformat()) # 2025-09-15T14:30:45.123456print("YYYY-MM-DD HH:MM:SS:", now.strftime("%Y-%m-%d %H:%M:%S"))print("DD/MM/YYYY HH:MM:", now.strftime("%d/%m/%Y %H:%M"))# Date onlyprint("Year-Month-Day:", now.strftime("%Y-%m-%d"))print("Day-Month-Year:", now.strftime("%d-%m-%Y"))print("Month/Day/Year:", now.strftime("%m/%d/%Y"))# Time onlyprint("24-hour format:", now.strftime("%H:%M:%S"))print("12-hour format:", now.strftime("%I:%M:%S %p"))# Named componentsprint("Weekday (short):", now.strftime("%a")) # Monprint("Weekday (full):", now.strftime("%A")) # Mondayprint("Month (short):", now.strftime("%b")) # Sepprint("Month (full):", now.strftime("%B")) # September# Other useful piecesprint("Day of month:", now.strftime("%d"))# 15print("Day of year:", now.strftime("%j")) # 258print("Week number:", now.strftime("%U")) # Week number of year (Sunday start)print("ISO Week number:", now.strftime("%V")) # Week number (ISO standard)print("Year (2-digit):", now.strftime("%y"))print("Year (4-digit):", now.strftime("%Y"))# Combiningprint("\nCustom combined format:", now.strftime("Today is %A, %B %d, %Y at %I:%M %p"))Demo of date and time objects
from datetime import date, time, datetime, timedelta# 1. Dated = date(2025, 9, 15)print("Date object:", d)today = date.today()print("Today's date:", today)print("Year:", today.year, "Month:", today.month, "Day:", today.day)# 2. Timet = time(14, 30, 45)print("\nTime object:", t)print("Hour:", t.hour, "Minute:", t.minute, "Second:", t.second)# 3. Datetime (date + time)dt = datetime(2025, 9, 15, 14, 30, 45)print("\nDatetime object:", dt)now = datetime.now()print("Current datetime:", now)print("Components:", now.year, now.month, now.day, now.hour, now.minute, now.second)# 4. Timedelta (date/time arithmetic)delta = timedelta(days=5, hours=3)future = now + deltapast = now - deltaprint("\nTimedelta:", delta)print("5 days and 3 hours later:", future)print("5 days and 3 hours earlier:", past)# 5. Formatting (datetime -> string)formatted = now.strftime("%Y-%m-%d %H:%M:%S")print("\nFormatted datetime string:", formatted)# 6. Parsing (string -> datetime)dt_str = "2025-09-15 14:30:45"parsed_dt = datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S")print("Parsed datetime from string:", parsed_dt)# 7. Comparisonsdt1 = datetime(2025, 1, 1)dt2 = datetime(2025, 12, 31)print("\nIs dt1 < dt2?", dt1 < dt2)print("Is today == now.date()?", today == now.date())Converting between timezones
You can use the zoneinfo module to convert between timezones:
- Create the
datetime - Attach the
timezonethat it represents - Use the
astimezonein combination with theZoneInfomethod to convert to the new datetime of the new timezone
Example:
from datetime import datetime, timezonefrom zoneinfo import ZoneInfo# Create a datetime object, will use UTC as an exampleutc_dt = datetime(2025, 9, 15, 12, 0, 0)# Attach the timezoneutc_dt = utc_dt.replace(tzinfo=timezone.utc)print("Stored in UTC:", utc_dt)# Convert UTC to London timelondon_dt = utc_dt.astimezone(ZoneInfo("Europe/London"))print("London:", london_dt)# Convert UTC to New York timeny_dt = utc_dt.astimezone(ZoneInfo("America/New_York"))print("New York:", ny_dt)print("London display:", london_dt.strftime("%Y-%m-%d %H:%M:%S %Z"))# London display: 2025-09-15 13:00:00 BSTprint("New York display:", ny_dt.strftime("%Y-%m-%d %H:%M:%S %Z"))# New York display: 2025-09-15 08:00:00 EDT