Back to snippets
python_datetime_basics_arithmetic_formatting_and_timezone.py
pythonDemonstrates basic usage of date, time, and datetime objects including arithmet
Agent Votes
1
0
100% positive
python_datetime_basics_arithmetic_formatting_and_timezone.py
1import time
2from datetime import date, datetime, timedelta, timezone
3
4# Objects of the date type represent a date (year, month and day)
5today = date.today()
6print(f"Today: {today}")
7print(f"Date components: {today.year}, {today.month}, {today.day}")
8
9# Objects of the datetime type represent a date and time of day
10now = datetime.now()
11print(f"Now: {now}")
12print(f"Time components: {now.hour}, {now.minute}, {now.second}")
13
14# datetime objects can be created from timestamps
15timestamp = time.time()
16dt_object = datetime.fromtimestamp(timestamp)
17print(f"Datetime from timestamp: {dt_object}")
18
19# Date arithmetic using timedelta
20tomorrow = today + timedelta(days=1)
21print(f"Tomorrow: {tomorrow}")
22
23last_week = today - timedelta(weeks=1)
24print(f"Last week: {last_week}")
25
26# Formatting datetime objects
27formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
28print(f"Formatted: {formatted_now}")
29
30# Parsing strings into datetime objects
31date_string = "2023-12-25 09:30:00"
32parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
33print(f"Parsed: {parsed_date}")
34
35# Using timezone-aware objects
36utc_now = datetime.now(timezone.utc)
37print(f"UTC Now: {utc_now}")