No Zero Padding with strftime()


O
ne of the best features of Python is that it is platform independent. You can write code on Linux, Windows, and MacOS and it works on all three platforms with no problems…mostly.

Admittedly there are some issues. Most of these are from known operating system differences when accessing system subprocesses or dealing with various local quirks of file systems and security schemes. These kinds of problems are expected. However, there are some lesser known problems that only emerge in very specific circumstances. One of these is controlling zero padding with the strftime() function in Python’s datetime module.

In most cases, zero-padding is needed and wanted. This is the case when formatting something like a date in a standard ISO 8601 calendar date format:

>>> from datetime import datetime
>>> d = datetime(2022, 1, 5)
>>> print(d.strftime("%Y-%m-%d"))
2022-01-05

But, what if you wanted to have this date displayed as “2022-1-5” instead? In other words, a date format without the zero-padding. How would you accomplish this? A quick look at the Python strftime() documentation notes that the “%m” and “%d” format codes always yield zero-padded results.

 

Python being Python, there is an easy solution to the immediate problem:

>>> s = d.strftime("%Y-%m-%d").replace("-0", "-")
>>> print(s)
2022-1-5

If you want a more general solution that handles various cases—like having strftime() produce the non-zero-padded results at the get go—you have to dig a little deeper. In this case, that means reading the Python strftime() documentation with care and noticing this detail:  

“The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation. There are also differences between platforms in handling of unsupported format specifiers.”

This is where Python’s platform independence ends:  at the C library that Python calls to perform the requested formatting service. If you look at the Windows C strftime() documentation, you will discover more options for formatting dates and times, including one that will remove the zero-padding:

>>> print(d.strftime("%Y-%#m-%#d"))  # Windows
2022-1-5

If you try the same thing on MacOS or Linux you get:

>>> print(d.strftime("%Y-%#m-%#d"))  # MacOS or Linux
2022-#m-#d

Reading the MacOS or Linux strftime() documentation reveals that ‘#’ is a valid formatting code modifier, but used for a different purpose on these platforms. Still you can see that it is mostly an overlapping set of formatting codes, with some differences from Windows. On these platforms, you will want to try using the dash () to indicate not padding a numeric result string.

>>> print(d.strftime("%Y-%-m-%-d"))  # MacOS or Linux
2022-1-5

If you try to run this version on Windows:

>>> print(d.strftime("%Y-%-m-%-d"))  # Windows
ValueError: Invalid format string

In this case, Windows raises an error and lets you know something is wrong.

Unless you run into this particular problem while trying to support multiple operating systems, this is mostly a cautionary tale about Python’s reliance on underlying C libraries to provide some of its lowest-level services. With that, you should keep in mind two key points:

  • First, Python may have access to (but no documentation for) some underlying features in the C library (like the no-zero-padding modifiers)—you may want or need to use these. It can be worth getting to know these C libraries
  • Second, the underlying C libraries sometimes behave differently on different operating systems.

Anyone trying to achieve true platform independence in these areas may have to work around those differences in some clever fashion.

About the Author

Eric Olsen holds a Ph.D. in history from the University of Pennsylvania, a M.S. in software engineering from Pennsylvania State University, and a B.A. in computer science from Utah State University. Eric spent three decades working in software development in a variety of fields, including atmospheric physics research, remote sensing and GIS, retail, and banking. In each of these fields, Eric focused on building software systems to automate and standardize the many repetitive, time-consuming, and unstable processes that he encountered.

Share this article:

Related Content

Digital Transformation in Practice

There is much more to digital transformation than technology, and a holistic strategy is crucial for the journey.

Read More

Leveraging AI for More Efficient Research in BioPharma

In the rapidly-evolving landscape of drug discovery and development, traditional approaches to R&D in biopharma are no longer sufficient. Artificial intelligence (AI) continues to be a...

Read More

Utilizing LLMs Today in Industrial Materials and Chemical R&D

Leveraging large language models (LLMs) in materials science and chemical R&D isn't just a speculative venture for some AI future. There are two primary use...

Read More

Top 10 AI Concepts Every Scientific R&D Leader Should Know

R&D leaders and scientists need a working understanding of key AI concepts so they can more effectively develop future-forward data strategies and lead the charge...

Read More

Why A Data Fabric is Essential for Modern R&D

Scattered and siloed data is one of the top challenges slowing down scientific discovery and innovation today. What every R&D organization needs is a data...

Read More

Jupyter AI Magics Are Not ✨Magic✨

It doesn’t take ✨magic✨ to integrate ChatGPT into your Jupyter workflow. Integrating ChatGPT into your Jupyter workflow doesn’t have to be magic. New tools are…

Read More

Top 5 Takeaways from the American Chemical Society (ACS) 2023 Fall Meeting: R&D Data, Generative AI and More

By Mike Heiber, Ph.D., Materials Informatics Manager Enthought, Materials Science Solutions The American Chemical Society (ACS) is a premier scientific organization with members all over…

Read More

Real Scientists Make Their Own Tools

There’s a long history of scientists who built new tools to enable their discoveries. Tycho Brahe built a quadrant that allowed him to observe the…

Read More

How IT Contributes to Successful Science

With the increasing importance of AI and machine learning in science and engineering, it is critical that the leadership of R&D and IT groups at...

Read More

From Data to Discovery: Exploring the Potential of Generative Models in Materials Informatics Solutions

Generative models can be used in many more areas than just language generation, with one particularly promising area: molecule generation for chemical product development.

Read More