Home The Quantizer> Python> Python: How to Get Today's Date

Python: How to Get Today's Date

The datetime module is a powerhouse for date and time operations in Python. To get today’s date, you can use the datetime.date.today() function.

from datetime import date

# Get today's date
today_date = date.today()

print("Today's date:", today_date)

This method is simple and effective, providing the date in the format YYYY-MM-DD.

Method 2: Using the datetime module with strftime

If you prefer a custom date format, you can use the strftime method to format the date as per your requirements.

from datetime import datetime

# Get today's date and format it
formatted_date = datetime.today().strftime('%Y-%m-%d')

print("Today's date:", formatted_date)

Here, %Y, %m, and %d represent the year, month, and day components, respectively. Adjust the format string to suit your needs.

Method 3: Epoch format

I find epoch format to be the easier to work with from a programmatic point of view. Having the date time as a single integer is easier to perform comparison and manipulations on. To get today’s date in epoch format (Unix timestamp) in Python, you can use the time module along with the datetime module. Here’s an example:

from datetime import datetime
import time

# Get today's date and time
today_datetime = datetime.today()

# Convert to epoch format (Unix timestamp)
epoch_format = int(today_datetime.timestamp())

print("Today's date in epoch format:", epoch_format)

Conclusion:

Obtaining today’s date in Python is a fundamental task in various applications. The datetime module provides the necessary tools for this, and whether you need a standard or custom format, Python has you covered. Choose the method that best fits your requirements and enhances your ability to work with dates effectively in your Python scripts.