Formatting DateTime objects

Sometimes we need to print our datetime objects in different formats. For these operations, we are going to use strftime() method. The syntax of strftime() is:

Syntax : strftime(format)

Python




# importing datetime object
import datetime
 
# initialising datetime object
obj = datetime.datetime(2001, 12, 9)
 
# Example 1
print(obj.strftime("%a %m %y"))
 
# Example 2
print(obj.strftime("%m-%d-%Y %T:%M%p"))


Output:

Sun 12 01
12-09-2001 00:00:00:00AM

We can get different attributes of the datetime object. In the code below, we are going to get the hours, minutes, and seconds.

Python




# importing datetime object
import datetime
 
# initialising datetime object
obj = datetime.datetime(2001, 12, 9, 12, 11, 23)
 
# Hours
print(obj.hour)
 
# Minutes
print(obj.minute)
 
# Seconds
print(obj.second)


Output:

12
11
23

We can also get a datetime object using the strptime() method, in which we get a DateTime object from a string. Since the strings we use can be formatted in any form, we need to specify the expected format. To understand this, let’s look at the syntax of strptime():

Syntax : datetime.strptime(data,expected_format)

Parameters

  • data : Our time and date passed as a string in a particular format
  • expected_format : the format in which data is presented in the first parameter

Python




# importing datetime object
import datetime
 
# using strptime() method
print(datetime.datetime.strptime("Jan 1, 2013 12:30 PM",
                                 "%b %d, %Y %I:%M %p"))


Output:

2013-01-01 12:30:00

Working with Datetime Objects and Timezones in Python

In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module.

Similar Reads

Getting a Datetime object

Method 1: Using now() method...

Formatting DateTime objects

...

Working with Timezones

...

Conversion of DateTime object from one Timezone to another

Sometimes we need to print our datetime objects in different formats. For these operations, we are going to use strftime() method. The syntax of strftime() is:...

Working with the timedelta class

...