Python Time and Date

In this tutorial you will learn:

  • Dates in Python
  • Time in Python
  • Converting datetime object to string
  • Calendar in Python

Dates in Python

In Python there are classes that gives us functions to manipulate dates and time. There are certain modules that are provided by Python and in order to bring those modules into our code we need to use import statements. These modules are called classes and they are containers that contain different functions. In order to work with date and time we need to import datetime function from date class.

from datetime import date

Creating a date object with known values

  1. import datetime
  2. print("Creating Date Object")
  3. d = datetime.date(2020,12,11)
  4. print("Created date object: ", d)

Getting the current date in Python

  1. from datetime import date
  2. dateToday = date.today()
  3. print("Date Today: ", dateToday)

Getting current date along with current timestamp

  1. from datetime import datetime
  2. now = datetime.now()
  3. print("Date time right now:", now)

Separately getting today's day, month and year

  1. from datetime import date
  2. dateToday = date.today()
  3. print("Month Today:", dateToday.month)
  4. print("Day Today:", dateToday.day)
  5. print("Year Today:", dateToday.year)

Time in Python

To get time in Python we need to import time function from the date time class.

Example:

  1. from datetime import time
  2. time = time(4, 15, 20)
  3. print("\n\nTime: ", time)
  4. print("Hour in time object: ", time.hour)
  5. print("Minutes in time object: ", time.minute)
  6. print("Seconds in time object: ", time.second)

Converting datetime object to string

In order to convert datetime object to string Python provides a function known as strftime function. It allows us to get time formatted string from a time object.

  1. from datetime import datetime
  2. now = datetime.now()
  3. dateTime1 = now.strftime("%m/%d/%Y, %H:%M:%S")
  4. print("Date in Month/Day/Year and time in Hour: Min: Sec: ", dateTime1)
Getting only time using strftime function
  1. time = now.strftime("%H:%M:%S")
  2. print("Time in Hour : Minute: Second :", time)

Calendar in Python

In order to get the calendar we need to import the calendar module on our code. This module gives us all functions of a calendar.

  1. print("\n\nCalendar in Python: ")
  2. import calendar
  3. cal = calendar.month(2020, 11)
  4. print(cal)

Comments

Submitted bySahana S.J (not verified)on Sat, 08/07/2021 - 14:11

boring

Add new comment