Python Get Current Date and Time

Python get current date and time; Through this tutorial, i will show you how to get the current date & time, get yesterday date, and how to get next day/date in python. And how to format the date and time in different formats by using python strftime() method.

How to get current date and time in Python

In this tutorial, i will show you how to get current date and time in python; as shown below:

  • 1: Python get the current date
  • 2: Current date in different formats
  • 3: Get the current date and time
  • 4: Python get yesterday date
  • 5: how to get next day date in python

1: Python get the current date

  • Import the date class from the datetime module.
  • After that, use date.today() method to get the current local date.
from datetime import date
today = date.today()
print("Today's date:", today)

After executing the program, the output will be:

Today's date: 2020-04-26 

2: Current date in different formats

from datetime import date
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)
# Textual month, day and year	
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)
# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)
# Month abbreviation, day and year	
d4 = today.strftime("%b-%d-%Y")
print("d4 =", d4)

After executing the program, the output will be:

d1 = 16/09/2019
d2 = September 16, 2019
d3 = 09/16/19
d4 = Sep-16-2019

3: Get the current date and time

If you need to get both the current date and time in python, you can use datetime class of the datetime module.

from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
 
print("now =", now)
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)	

After executing the program, the output will be:

now = 2020-04-26 12:29:27.316232
date and time = 26/04/2020 12:29:27

4: Python get yesterday date

from datetime import date
from datetime import timedelta 
# Get today's date 
today = date.today() 
print("Today is: ", today) 
  
# Yesterday date 
yesterday = today - timedelta(days = 1) 
print("Yesterday was: ", yesterday) 

After executing the program, the output will be:

Today is:  2020-04-26
Yesterday was:  2020-04-25

5: how to get next day date in python

from datetime import date
from datetime import timedelta 
# Get today's date 
today = date.today() 
print("Today is: ", today) 
  
# Yesterday date 
yesterday = today + timedelta(days = 1) 
print("Next date will be : ", yesterday) 

After executing the program, the output will be:

Today is:  2020-04-26
Next date will be :  2020-04-27

Recommended Python Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *