runtime
101 / 250
lesson 101 Dates Numbers & Regex · intermediate

Read and write dates and times

A timestamp in a file is just text. `datetime.strptime` reads it with a format you spell out, giving a value you can ask for its weekday or compare; `strftime` writes it back in any layout.

You'll be able to
  • Parse timestamps with datetime.strptime(text, format) using %Y %m %d %H %M %S
  • Read parts of a datetime (year, month, weekday()) and format it with strftime
  • Recognise the ValueError for text that doesn't match, and the silent %m/%M mix-up
The idea

"2024-01-03 18:35:10" looks like a time, but to Python it's ten digits and some punctuation: you can't ask it for the weekday, compare it properly with "2024-1-4 9:00", or add a day to it.

from datetime import datetime, then datetime.strptime(text, format) (string parse time) reads the text using a format made of codes: %Y four-digit year, %m month number, %d day, %H hour (00–23), %M minute, %S second, %b a short month name like Jan. Everything else in the format must appear in the text exactly. The result is a datetime, and value.strftime(format) (string format time) writes it back out in whatever layout a report needs.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · An order timestamp, taken apart
from datetime import datetime

ordered = datetime.strptime("2024-01-03 18:35:10", "%Y-%m-%d %H:%M:%S")
print(ordered)
print(ordered.year, ordered.month, ordered.day, ordered.hour)
print(ordered.strftime("%d %b %Y, %H:%M"))
print(ordered.strftime("%A"), ordered.weekday())
example-2.py · Text that doesn't match the format
from datetime import datetime

due = datetime.strptime("01/03/2024", "%Y-%m-%d")

Once timestamps are datetimes, questions about them become one line each. This function counts orders per weekday, the kind of figure that decides when a shop schedules staff.

example-3.py · Orders per weekday
from datetime import datetime

def orders_per_weekday(timestamps):
    counts = {}
    for text in timestamps:
        day = datetime.strptime(text, "%Y-%m-%d %H:%M:%S").strftime("%A")
        counts[day] = counts.get(day, 0) + 1
    return counts

print(orders_per_weekday([
    "2024-01-03 18:35:10",
    "2024-03-13 17:16:09",
    "2024-08-23 04:08:40",
    "2024-12-03 23:16:00",
    "2024-12-21 19:58:19",
]))

When to use it: whenever dates arrive as text (CSV columns, logs, forms) and you need to compare them, group them or show them differently. ISO text like 2024-01-03 18:35:10 can also be read with datetime.fromisoformat(text). Mistakes to avoid: %M (minutes) where you meant %m (month), which parses without any error and gives the wrong date; and guessing whether 01/03 is day-first or month-first instead of knowing where the data came from.

Review
  • datetime.strptime(text, format) parses; value.strftime(format) formats. The format must match the text exactly.
  • %Y %m %d %H %M %S are year, month, day, hour, minute, second; %m and %M are easy to swap.
  • weekday() is 0 for Monday through 6 for Sunday.
  • Next: a time only means something with its time zone.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Read and write dates and times — Dates Numbers & Regex · Runtime