Dates & Times

Python - A Quick Start for existing Programers

3 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

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, timedelta




date object

Creation:

# Create a date using year, month, day
d1 = date(2025, 9, 15)
print("Date from year, month, day:", d1)

# Get today's date
d2 = date.today()
print("Today's date:", d2)

# Create a date from a timestamp (seconds since epoch)
ts = 1694764800 # example timestamp
d3 = date.fromtimestamp(ts)
print("Date from timestamp:", d3)

# Create a date from an ISO string
iso_str = "2025-09-15"
d4 = date.fromisoformat(iso_str)
print("Date from ISO string:", d4)

Attributes:

  • year, month, day

Methods:

  • today() → current date
  • fromtimestamp(ts) → date from Unix timestamp
  • weekday() → 0=Monday … 6=Sunday
  • isoweekday() → 1=Monday … 7=Sunday
  • isoformat() → 'YYYY-MM-DD'
  • replace(year=…, month=…, day=…) → return new date with replaced fields
  • timetuple() → struct_time tuple

Operations:

  • date1 - date2timedelta
  • Comparisons: <, >, ==, etc.



time object

Creation:

# Create a time using hour, minute, second, microsecond
t1 = time(14, 30, 45)
print("\nTime from h,m,s:", t1)

# Create a time with microseconds
t2 = time(14, 30, 45, 123456)
print("Time with microseconds:", t2)

# Replace components of a time object
t3 = t1.replace(hour=16, minute=0)
print("Time after replace:", t3)

# Get current time as a time object
current_time = datetime.now().time()
print("Current time:", current_time)

# Get current UTC time as a time object
current_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, microsecond
dt1 = datetime(2025, 9, 15, 14, 30, 45)
print("\nDatetime from components:", dt1)

# Current local datetime
dt2 = datetime.now()
print("Current local datetime:", dt2)

# Current UTC datetime
dt3 = datetime.utcnow()
print("Current UTC datetime:", dt3)

# Create datetime from timestamp
dt4 = datetime.fromtimestamp(ts)
print("Datetime from timestamp:", dt4)

# Create datetime from ISO string
dt5 = datetime.fromisoformat("2025-09-15T14:30:45")
print("Datetime from ISO string:", dt5)

# Create datetime from a date and time object
d1 = date(2025, 9, 15)
t1 = time(14, 30, 45)
dt6 = datetime.combine(d1, t1)
print("Datetime from date + time objects:", dt6)

# Replace components of datetime
dt7 = dt1.replace(year=2026, hour=16)
print("Datetime after replace:", dt7)

Attributes:

  • year, month, day, hour, minute, second, microsecond, tzinfo

Methods:

  • date() → date part
  • time() → time part
  • replace(...) → replace components
  • isoformat() → 'YYYY-MM-DDTHH:MM:SS.microseconds'
  • strftime(format) → formatted string
  • strptime(string, format) → parse string into datetime
  • timestamp() → seconds since epoch

Operations:

  • datetime ± timedelta → new datetime
  • datetime1 - 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 datetime
  • datetime - timedelta → new datetime
  • timedelta ± 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

%Y

Year (4 digits)

2025

%y

Year (2 digits)

25

%m

Month (01–12)

09

%B

Full month name

September

%b

Abbreviated month name

Sep

%d

Day of month (01–31)

15

%j

Day of year (001–366)

258

%U

Week number of year (Sunday as first day, 00–53)

37

%W

Week number of year (Monday as first day, 00–53)

37

%V

ISO week number (01–53)

38

%A

Full weekday name

Monday

%a

Abbreviated weekday name

Mon

%w

Weekday as number (0=Sunday, 6=Saturday)

1

%x

Locale’s date representation

09/15/25

%H

Hour (00–23)

14

%I

Hour (01–12)

02

%p

AM/PM

PM

%M

Minute (00–59)

30

%S

Second (00–59)

45

%f

Microsecond (000000–999999)

123456

%X

Locale’s time representation

14:30:45

%c

Locale’s date and time

Mon Sep 15 14:30:45 2025

%x

Locale’s date

09/15/25

%X

Locale’s time

14:30:45

%%

A literal % character

%


Examples:

from datetime import datetime

# Get current datetime
now = datetime.now()
print("Original datetime object:", now)

print("\n# Common formats")

# Full date & time
print("Default ISO:", now.isoformat())
# 2025-09-15T14:30:45.123456
print("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 only
print("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 only
print("24-hour format:", now.strftime("%H:%M:%S"))
print("12-hour format:", now.strftime("%I:%M:%S %p"))

# Named components
print("Weekday (short):", now.strftime("%a"))
# Mon
print("Weekday (full):", now.strftime("%A"))
# Monday
print("Month (short):", now.strftime("%b"))
# Sep
print("Month (full):", now.strftime("%B"))
# September

# Other useful pieces
print("Day of month:", now.strftime("%d"))
# 15
print("Day of year:", now.strftime("%j"))
# 258
print("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"))

# Combining
print("\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. Date
d = 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. Time
t = 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 + delta
past = now - delta
print("\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. Comparisons
dt1 = 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 timezone that it represents
  • Use the astimezone in combination with the ZoneInfo method to convert to the new datetime of the new timezone

Example:

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

# Create a datetime object, will use UTC as an example
utc_dt = datetime(2025, 9, 15, 12, 0, 0)

# Attach the timezone
utc_dt = utc_dt.replace(tzinfo=timezone.utc)
print("Stored in UTC:", utc_dt)

# Convert UTC to London time
london_dt = utc_dt.astimezone(ZoneInfo("Europe/London"))
print("London:", london_dt)

# Convert UTC to New York time
ny_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 BST
print("New York display:", ny_dt.strftime("%Y-%m-%d %H:%M:%S %Z"))
# New York display: 2025-09-15 08:00:00 EDT
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact