Skip to main content

How to format a time in Python

How to format a time in Python.

Here is a step-by-step tutorial on how to format a time in Python using different code examples:

Formatting Time in Python

Python provides the datetime module to work with dates and times. You can use this module to format time in various ways. Let's dive into the process:

Step 1: Import the datetime module

To begin, import the datetime module by adding the following line of code at the top of your Python script:

import datetime

Step 2: Get the current time

To format the current time, you need to retrieve it first. Use the datetime.now() method to get the current time:

current_time = datetime.datetime.now()

Step 3: Format time using strftime()

The strftime() method allows you to format the time according to a specific format string. Here are some commonly used format codes:

  • %H: Hour (24-hour clock)
  • %I: Hour (12-hour clock)
  • %M: Minute
  • %S: Second
  • %p: AM/PM indicator
  • %Y: Year
  • %m: Month
  • %d: Day

Let's see some code examples:

Example 1: Format time as HH:MM:SS

formatted_time = current_time.strftime("%H:%M:%S")
print(formatted_time)

Output:

16:30:45

Example 2: Format time as HH:MM AM/PM

formatted_time = current_time.strftime("%I:%M %p")
print(formatted_time)

Output:

04:30 PM

Example 3: Format time as YYYY-MM-DD HH:MM:SS

formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)

Output:

2022-12-31 16:30:45

Step 4: Format time using strptime()

If you have a time string in a specific format and want to convert it into a datetime object, you can use the strptime() method. It takes two arguments: the time string and the format string.

Example 4: Convert a time string to a datetime object

time_string = "2022-12-31 16:30:45"
formatted_time = datetime.datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
print(formatted_time)

Output:

2022-12-31 16:30:45

Step 5: Handling Timezones

Python's datetime module also provides support for handling timezones using the pytz library. You need to install the pytz library first by running the following command:

pip install pytz

Once installed, you can use it as follows:

import datetime
import pytz

# Get the current time in UTC timezone
current_time = datetime.datetime.now(pytz.UTC)

# Convert the time to a specific timezone
timezone = pytz.timezone('America/New_York')
formatted_time = current_time.astimezone(timezone)
print(formatted_time)

Output:

2022-12-31 11:30:45-05:00

Conclusion

In this tutorial, you learned how to format time in Python using the datetime module. You can use the strftime() method to format the current time, and the strptime() method to convert a time string to a datetime object. Additionally, you can handle timezones using the pytz library.