How to work with datetime in Python

How to get the current date in Python

from datetime import datetime

# Get current date
date_today = datetime.now()

# Print current date
print(date_today)

How to convert the current date to a timestamp in Python

from datetime import datetime

# Get current date
date_today = datetime.now()

timestamp = date_today.timestamp()

# Print the timestamp
print(timestamp)

How to convert a timestamp back to a datetime in Python

from datetime import datetime

# Example timestamp
timestamp = 1672531199

date_from_timestamp = datetime.fromtimestamp(timestamp)

# Print the datetime
print(date_from_timestamp)

How to add an interval to a datetime in Python

from datetime import datetime, timedelta

# Get current date
date_today = datetime.now()

# Add 5 days
new_date = date_today + timedelta(days=5)

# Print the new date
print(new_date)

How to format a date with time in Python

from datetime import datetime

# Get current date
date_today = datetime.now()

# Format date with time
formatted_date_with_time = date_today.strftime('%Y-%m-%d %H:%M:%S')

# Print formatted date
print(formatted_date_with_time)

How to format a date without time in Python

from datetime import datetime

# Get current date
date_today = datetime.now()

# Format date without time
formatted_date_without_time = date_today.strftime('%Y-%m-%d')

# Print formatted date
print(formatted_date_without_time)

Where to go next: