1.

Formatting Dates in Python

Answer»

To handle date and time operations in Python, we use the datetime module.


  • time class: We can represent time values using the time class.

   Example:

import datetime
tm = datetime.time(1, 30, 11, 22)
print(tm)
Output:
01:30:11.000022

  • date class: We can represent date values using the date class.

   Example:

import datetime
date = datetime.date(2000, 11, 16)
print('Date date is ', date.day, ' day of ', date.month, ' month of the year ', date.year)
Output:
Date date is 16 day of 11 month of the year 2000

  • Conversion from date to time: We can convert a date to its corresponding time using the strptime() function.

   Example:

from datetime import datetime
print(datetime.strptime('15/11/2000', '%d/%m/%Y'))
Output:
2000-11-15 00:00:00

  • time.strftime() in Python: It converts a tuple or struct_time representing the time into a string object.

   For example:

from time import gmtime, strftime
s = strftime("%a, %d %b %Y %H:%M:%S + 1010", gmtime())
print(s)
Output:
Sun, 28 Nov 2021 18:51:24 + 1010


Discussion

No Comment Found