Introduction

Working with dates and time in Python is an essential skill for any Python developer, as it allows for powerful time-based computations and analysis. This tutorial will cover the basics of working with dates and time in Python. By the end of this tutorial, you will have a deeper understanding of how to work with dates and time in Python and be able to apply these tools to your own projects.

Table of Contents :

  • Today's Date in Python
  • Current Date in Different Formats
  • Get the Current Date and Time in Python

Today's Date in Python:

  • The  date  class in Python's datetime module can be used to represent and manipulate dates.
  • The  today()  method of the date class returns the current date.
  • Code Sample :

from datetime import date

today = date.today()
print("Today's date:", today)

# Output: Today's date: 2022-03-07

Current Date in Different Formats:

  • strftime() method can be used to format dates in various formats.
  • Here are some examples:

from datetime import datetime

# Formats: year, month, day
print(datetime.now().strftime("%Y-%m-%d"))
print(datetime.now().strftime("%d-%m-%Y"))
print(datetime.now().strftime("%A %d %B %Y"))

# Output:  

2022-03-07
07-03-2022
Monday 07 March 2022

Get the Current Date and Time in Python:

  • The datetime class in the datetime module can be used to represent and manipulate dates and times together.
  • The now() method of the datetime class returns the current date and time.
  • Example code:

from datetime import datetime

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

Prev. Tutorial : Using datetime.strptime()

Next Tutorial : Current date-time