All categories
    PythonIntermediate

    Dates & Times

    Python datetime module: create dates, format with strftime, add timedeltas, parse strings, and calculate differences between dates.

    01Create and format a date

    main.py
    from datetime import date
    d = date(2024, 1, 15)
    print(d.year)
    print(d.strftime("%B %d, %Y"))
    Output
    2024
    January 15, 2024

    02Add days with timedelta

    main.py
    from datetime import date, timedelta
    start = date(2024, 1, 1)
    later = start + timedelta(days=30)
    print(later)
    Output
    2024-01-31

    03Difference between dates

    main.py
    from datetime import date
    d1 = date(2024, 3, 1)
    d2 = date(2024, 1, 1)
    print((d1 - d2).days)
    Output
    60

    04Parse a date string

    main.py
    from datetime import datetime
    dt = datetime.strptime("2024-06-15", "%Y-%m-%d")
    print(dt.month)
    Output
    6