Python: Dates and times

This documentation is part of the Learning Python guide. View the full guide here: A comprehensive Python guide.

👋 Welcome to the Stackhero documentation!

Stackhero provides a ready-to-use Python cloud solution designed to streamline your deployment process:

  • Deploy your application to production in seconds with a simple git push.
  • Use your own domain name, with automatic HTTPS certificate configuration for secure connections handled for you.
  • Rely on automatic backups, one-click updates, and predictable pricing, so you can focus on your code, not infrastructure management.
  • Benefit from strong performance and security on a private, dedicated infrastructure. Your environment is isolated and protected.

Save time and simplify your workflow: you can have your code running with Stackhero's Python cloud hosting in just 5 minutes.

Working with dates and times is a common requirement, especially for data analysis or scheduling tasks. The datetime module provides classes and functions to work with dates, times, and intervals.

import datetime

# datetime, date, time, timedelta, timezone

Examples:

from datetime import datetime, timedelta

# Current date and time
current_time = datetime.now()
print("Current date and time:", current_time)

# Custom date and time
custom_date = datetime(2022, 12, 31, 23, 59, 59)
print("Custom date and time:", custom_date)

# Convert string to datetime
date_str = "2023-01-01 00:00:00"
date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("String to datetime:", date_obj)

# Convert datetime to string
date_str2 = date_obj.strftime("%Y-%m-%d %H:%M:%S")
print("Datetime to string:", date_str2)

# Date and time arithmetic
one_day = timedelta(days=1)
yesterday = current_time - one_day
tomorrow = current_time + one_day
print("Yesterday:", yesterday)
print("Tomorrow:", tomorrow)