How to get formatted date and time in Python?


In this article, we will show you how to format date and time in python.

The datetime module in Python offers methods for working with date and time values. To use this module, we must first import it using the following import keyword

import datetime

strftime function()

The strftime() function returns a formatted date and time. It accepts a format string that you can use to get the result you want. The following are the directives that it supports.

Directive Meaning
%a Locale's abbreviated weekday name
%B Locale's full month name.
%c Locale's appropriate date and time representation
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale's equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x Locale's appropriate date representation.
%X Locale's appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal "%" character

Strftime() Function of a datetime class

Using a date, time, or datetime object, the strftime() method returns a string representing the date and time.

To convert a datetime object into a string using the specified format, use datetime.strftime(format).

The format codes are standard directives for specifying the format in which you want to represent datetime. The %d-%m-%Y%H:%M:%S codes, for example, convert dates to dd-mm-yyyy hh:mm:ss format.

Example

from datetime import datetime # getting the current date and time current_datetime = datetime.now() # getting the year from the current date and time current_year = current_datetime.strftime("%Y") print("current year = ", current_year) # getting the month from the current date and time current_month = current_datetime.strftime("%m") print("current month = ", current_month) # getting the day/date from the current date and time current_day = current_datetime.strftime("%d") print("current day = ", current_day) # getting the time from the current date and time in the given format current_time = current_datetime.strftime("%H:%M:%S") print("current time = ", current_time) # getting the date and time from the current date and time in the given format current_date_time = current_datetime.strftime("%m/%d/%Y, %H:%M:%S") print("current date and time = ",current_date_time)

Output

current year = 2022
current month = 08
current day = 15
current time = 17:49:46
current date and time = 08/15/2022, 17:49:46

Note: If the program is running on an online editor it shows GMT time, where as if the program is running on Local System Editor, it will show the time displayed on your own

Time class

The time class can be used to represent time values. The hour, minute, second, and microsecond are time class attributes.

Syntax

time(hour, minute, second, microsecond)

Example 1

import datetime # formating time format_time = datetime.time(3, 12, 24, 10) print(format_time)

Output

03:12:24.000010

There are time attribute ranges, for example, seconds have a range of 0 to 59 and nanoseconds have a range of 0 to 999999. If the range is too large, the compiler displays a ValueError

The instance of the time class has three instance attributes: hour, minute, second, and microsecond. These are used to obtain specific time information

Example 2

import datetime # formating time format_time = datetime.time(3, 12, 24, 10) # Printing time in the formating of time attributes print('Time:', format_time.hour,' hours ', format_time.minute,' minutes ', format_time.second,'seconds and ', format_time.microsecond,'microseconds' )

Output

Time: 3 hours 12 minutes 24 seconds and 10 microseconds

Date class

The calendar date values can be represented using the date class. The date instance is made up of the year, month, and day attributes.

Syntax

date(yyyy, mm, dd)

Example 1

import datetime # formating date format_date = datetime.date(2005, 4, 16) # Printing date in the formating of date attributes print('Date:', format_date.day, 'day,', format_date.month, 'month and', format_date.year, 'year')

Output

Date: 16 day, 4 month and 2005 year

Convert date to string

Because dates and times differ from strings, it is frequently necessary to convert the datetime to a string. We utilise the strftime() function for this.

Syntax

time.strftime(format, t)

Parameters

format- String type. The directives can be included in the format string

time - time that should be formatted

Example

import datetime # formating date and time format_datetime = datetime.datetime(2005, 4, 16, 3, 22, 30, 8) # Printing date & time in the formating of date and time attributes print(format_datetime.strftime("%b %d %Y %H:%M:%S"))

Output

Apr 16 2005 03:22:30

The symbols %H,%M, and %S represent the hour, minutes, and seconds, respectively. The characters %b, %d, and %Y represent the month, day, and year, respectively.

Convert string to date

Conversion from string to date is frequently required when working with imported data sets from a csv or taking inputs from website forms. Python has a function called strptime() to accomplish this.

Syntax

datetime.strptime(string, format)

Parameters

string- string that should be formatted

format - String type. The directives can be included in the format string.

Example

from datetime import datetime # converting input string to date format(date-month-year format) print(datetime.strptime('16/5/2005', '%d/%m/%Y'))

Output

2005-05-16 00:00:00

Conclusion

We learned how to format date and time in Python using the datetime module. We also learned how to format date by converting it to a string and then back to a date.

Updated on: 02-Sep-2023

88K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements