Strftime Python Tutorial – Complete Guide

Welcome to this comprehensive tutorial on strftime in Python. Strftime stands for “string format time”, a method that helps modify and control the output format of dates and time in Python. Having control over this aspect of your code can be crucial whether you’re designing a game that needs a real-world timestamp, or you’re coding a project that involves scheduling and time tracking.

What is Strftime in Python?

Strftime is a method in Python that converts a datetime object into a string with a specified format. Working within the datetime module, this function allows you to present time-related data in a more readable or personalized format.

Understanding strftime and how to wield its power can give your projects a professional edge, while also making them more user-friendly. If you’re looking to create a game where players can see their exact completion time in a format they recognize, or if you’re creating an application that sends scheduled notifications, mastering strftime can be the key. So, let’s dive in and unravel the mystery of strftime in Python.

This knowledge of strftime isn’t just for beginners, it’s also a valuable tool for experienced Python coders, as it adds another layer of detail and personalization to any time-sensitive project.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Strftime Basics – How to Use It?

Let’s kick off with a simple example where we convert the current date and time into a formatted string.

import datetime

current_date_time = datetime.datetime.now()
formatted_date_time = current_date_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date_time)

In this piece of code, `%Y-%m-%d %H:%M:%S` is the format string. Each special character preceded by a `%` corresponds to a specific element of the date or time. Here, we’re specifying year, month, day, hours, minutes, and seconds.

Next, let’s explore a few commonly used strftime directives:

current_date_time = datetime.datetime.now()

# Get the year in four digits
print(current_date_time.strftime("%Y"))

# Get the year in two digits
print(current_date_time.strftime("%y"))

# Get the month as a zero-padded decimal 
print(current_date_time.strftime("%m"))

# Get the day of the month as a zero-padded decimal
print(current_date_time.strftime("%d"))

# Get the weekday as a locale’s abbreviated name
print(current_date_time.strftime("%a"))

Advanced Strftime Usage Examples

Beyond the basic year, month, day, hours, minutes, seconds, Python offers an array of other directives you can use to meet your unique requirements.

Let’s convert the current date and time into more complex formats:

current_date_time = datetime.datetime.now()

# Get the date in the format 'MM/DD/YY'
print(current_date_time.strftime("%m/%d/%y"))

# Get the date in the format 'Month Day, Year'
print(current_date_time.strftime("%B %d, %Y"))

# Get the time in the 12-hour clock
print(current_date_time.strftime("%I:%M:%S %p"))

# Get the full date and time
print(current_date_time.strftime("%c"))

In this way, we can use strftime to format our date and time into almost any configuration we can imagine. Learning strftime in Python allows us to have more control over how we represent time in our code, providing our programs with added flexibility and usability.

Datetime Objects with Strftime

Let’s now look at how to use strftime to convert datetime objects into formatted strings.

# Creating a datetime object for a specific date and time
my_date_time = datetime.datetime(2020, 5, 17, 23, 45, 12)

# Convert it into a string with the format 'YYYY-MM-DD HH:MM:SS'
print(my_date_time.strftime("%Y-%m-%d %H:%M:%S"))

# Convert it into the format 'MM/DD/YY HH:MM:SS'
print(my_date_time.strftime("%m/%d/%y %H:%M:%S"))

# Convert to the format 'Month Day, Year at HH:MM:SS'
print(my_date_time.strftime("%B %d, %Y at %H:%M:%S"))

With strftime, datetime objects can be converted into more meaningful and user-friendly strings based on your application preference.

Strftime with Locale’s Full Weekday and Month Name

Let’s see how we can get the locale’s full weekday and month name using strftime.

current_date_time = datetime.datetime.now()

# Get the weekday as a locale’s full name
print(current_date_time.strftime("%A"))

# Get the month as a locale’s full name
print(current_date_time.strftime("%B"))

These strftime directives are especially handy when your application needs to display full names for weekdays or months.

Strftime Week and Year Directives

Python’s strftime also includes directives for week and year.

current_date_time = datetime.datetime.now()

# Get the week number of the year (Sunday as the first day of the week)
print(current_date_time.strftime("%U"))

# Get the week number of the year (Monday as the first day of the week)
print(current_date_time.strftime("%W"))

# Get the year for the week where Monday is the first day of the week
print(current_date_time.strftime("%G"))

# Get the year for the week where Sunday is the first day of the week
print(current_date_time.strftime("%Y"))

Here, you’ll notice two sets of directives for the week of the year and its corresponding year. The difference lies in the first day of the week— either Sunday or Monday.

Strftime with Locale’s Appropriate Date and Time Representation

Last but not least, let’s display the date and time in the format appropriate for the current locale, using strftime:

current_date_time = datetime.datetime.now()

# Get the locale’s appropriate date representation
print(current_date_time.strftime("%x"))

# Get the locale’s appropriate time representation
print(current_date_time.strftime("%X"))

This is essential for applications that are used across different locales, as it improves user readability and localization.

Where to Go Next?

Now that you’ve grasped the basics of strftime in Python, don’t stop here. There’s a lot more for us to unravel and explore together.

We wholeheartedly invite you to check out our Python Mini-Degree. This collection consists of comprehensive coursework that covers width and breadth of Python, a highly-popular language known for its simplicity and versatility. The course structure includes everything from coding basics, algorithms, and object-oriented programming, to game development and app development.

Each element of this degree is designed keeping the following benefits in mind:

  • Students learn via engaging hands-on projects, where they create games, algorithms, and real-world apps.
  • The degree aids in building a solid portfolio of Python projects which adds immense value to your resume.
  • The courses are suitable for both beginners and experienced programmers.
  • All our courses are flexible and accessible 24/7, which means you can learn as per your convenience.
  • Apart from the video lessons, we also have quizzes and completion certificates to ensure a holistic learning experience.
  • The joyous part, many of our students have either changed their careers or even ventured into starting their own businesses after completing these courses.

Additionally, for those seeking to widen their Python skills, don’t forget to explore our broad collection of Python courses.

Conclusion

Whether you want to add a precise timestamp to your games, write a scheduling project, or simply explore the mechanics of Python’s datetime module, understanding strftime will certainly equip you with an additional edge. Offering flexibility and precision, it boosts the level of sophistication and user-friendliness in your applications.

Always remember, we, at Zenva, are eager to support your learning journey. Our Python Mini-Degree course offers extensive coverage of Python, providing a robust foundation for those who seek to dive deep into programming or game development. Don’t wait to dive in and broaden your horizons; an exciting world of coding awaits!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.