Python22 min read

Python Datetime

Learn datetime step by step: date vs datetime, parsing strings, formatting, and doing time arithmetic correctly.

Michael Brown
August 29, 2025
5.1k230

Dates and times are tricky in every language. Python provides the datetime module to handle them safely.

  You will commonly do four things:
  1) get the current time
  2) convert a string into a date (parsing)
  3) format a date into a string
  4) add/subtract time (timedelta)
  
  ## Date vs datetime (important difference)
  
  - `date`: only year-month-day
  - `datetime`: year-month-day + hours-minutes-seconds
  
  ## Get current date and time
  
  ```python
  from datetime import datetime, date
  
  now = datetime.now()
  today = date.today()
  
  print(now)
  print(today)
  ```
  
  Expected output example:
  
  ```
  2025-12-18 14:30:45.123456
  2025-12-18
  ```
  
  ## Create a specific date/time
  
  ```python
  from datetime import datetime
  
  birthday = datetime(1995, 6, 15, 9, 30)  # June 15, 1995 09:30
  print(birthday)
  ```
  
  Expected output:
  
  ```
  1995-06-15 09:30:00
  ```
  
  ## Parse a date string (strptime)
  
  You must match the pattern exactly.
  
  ```python
  from datetime import datetime
  
  date_str = "2025-12-18"
  date_obj = datetime.strptime(date_str, "%Y-%m-%d")
  
  print(date_obj)
  ```
  
  Expected output:
  
  ```
  2025-12-18 00:00:00
  ```
  
  ## Format a date into a string (strftime)
  
  ```python
  from datetime import datetime
  
  now = datetime(2025, 12, 18, 14, 30)
  
  print(now.strftime("%B %d, %Y"))  # Month day, Year
  print(now.strftime("%m/%d/%Y"))   # US format
  print(now.strftime("%Y-%m-%d"))   # ISO-like
  ```
  
  Expected output:
  
  ```
  December 18, 2025
  12/18/2025
  2025-12-18
  ```
  
  ## Date arithmetic (timedelta)
  
  ```python
  from datetime import datetime, timedelta
  
  today = datetime(2025, 12, 18)
  
  tomorrow = today + timedelta(days=1)
  last_week = today - timedelta(weeks=1)
  
  print(tomorrow)
  print(last_week)
  ```
  
  Expected output:
  
  ```
  2025-12-19 00:00:00
  2025-12-11 00:00:00
  ```
  
  ## Graph: parsing and formatting
  
  ```mermaid
  flowchart LR
    A["'2025-12-18' (string)"] -->|strptime| B[datetime object]
    B -->|strftime| C["'December 18, 2025' (string)"]
    B -->|+ timedelta| D[new datetime]
  ```
  
  ## Beginner warning: time zones
  
  This lesson uses local time for simplicity. In real apps, time zones matter a lot. The safest professional approach is:
  - store timestamps in UTC
  - convert to local time only when showing to the user
  
  In the next lesson, you will learn regex, which helps you validate and extract information from text like emails, phone numbers, and IDs.
#Python#Intermediate#Datetime