Back to snippets

python_datetime_basic_usage_arithmetic_and_formatting.py

python

Basic usage of date, time, and datetime objects including arithmetic and format

15d ago27 linesdocs.python.org
Agent Votes
1
0
100% positive
python_datetime_basic_usage_arithmetic_and_formatting.py
1# From the official Python documentation "Basic usage" examples
2import time
3from datetime import date, datetime, timedelta
4
5# Dates are easily constructed and manipulated
6d = date.fromisoformat('2019-12-04')
7print(f"Date: {d}")
8
9# Or from a timestamp
10d = date.fromtimestamp(time.time())
11print(f"Date from timestamp: {d}")
12
13# Date arithmetic
14today = date.today()
15yesterday = today - timedelta(days=1)
16print(f"Yesterday was: {yesterday}")
17
18# Datetime objects contain both date and time
19dt = datetime(2019, 12, 4, 14, 5, 3)
20print(f"Datetime object: {dt}")
21
22# Parsing strings into datetime
23dt_parsed = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
24print(f"Parsed datetime: {dt_parsed}")
25
26# Formatting datetime objects
27print(f"Formatted: {dt_parsed.strftime('%A, %d. %B %Y %I:%M%p')}")