DEV Community

Avnish
Avnish

Posted on

How to get current date and time in Python?

How to Get Current Date and Time in Python

Python provides several convenient ways to fetch the current date and time using the datetime module.


1. Get Today's Date

To get the current local date, use the date class from the datetime module.

Example 1:

from datetime import date

# Get today's date
today = date.today()
print("Today's date:", today)
Enter fullscreen mode Exit fullscreen mode

Output:

Today's date: 2022-12-27
Enter fullscreen mode Exit fullscreen mode
  • date.today(): Fetches the current date in the format YYYY-MM-DD.

2. Current Date in Different Formats

The strftime() method lets you format the date in various styles.

Example 2:

from datetime import date

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

# Different formats
d1 = today.strftime("%d/%m/%Y")  # Day/Month/Year
print("d1 =", d1)

d2 = today.strftime("%B %d, %Y")  # Full Month Name
print("d2 =", d2)

d3 = today.strftime("%m/%d/%y")  # Month/Day/Short Year
print("d3 =", d3)

d4 = today.strftime("%b-%d-%Y")  # Month Abbreviation
print("d4 =", d4)
Enter fullscreen mode Exit fullscreen mode

Output:

d1 = 27/12/2022  
d2 = December 27, 2022  
d3 = 12/27/22  
d4 = Dec-27-2022  
Enter fullscreen mode Exit fullscreen mode

3. Get Current Date and Time

To fetch both the current date and time, use the datetime class.

Example 3:

from datetime import datetime

# Get current date and time
now = datetime.now()

print("now =", now)  # Default format (YYYY-MM-DD HH:MM:SS.microseconds)

# Format date and time
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")  # Day/Month/Year Hour:Minute:Second
print("date and time =", dt_string)
Enter fullscreen mode Exit fullscreen mode

Output:

now = 2022-12-27 10:09:20.430322  
date and time = 27/12/2022 10:09:20  
Enter fullscreen mode Exit fullscreen mode

Key Date and Time Format Codes

Format Code Description Example Output
%d Day of the month 27
%m Month (numeric) 12
%B Full month name December
%b Month abbreviation Dec
%Y Year (4 digits) 2022
%y Year (last 2 digits) 22
%H Hour (24-hour clock) 10
%M Minutes 09
%S Seconds 20

Summary

  • Use date.today() for just the current date.
  • Use datetime.now() for both date and time.
  • Format output with strftime() to suit your needs.

These methods provide flexibility and are easy to use for various date and time operations in Python.

Top comments (0)