Explain Codes LogoExplain Codes Logo

Python datetime to string without microsecond component

python
datetime
formatting
python-3.6
Nikita BarsukovbyNikita Barsukov·Aug 31, 2024
TLDR

Here's the magic spell: use strftime with the format "%Y-%m-%d %H:%M:%S" to transform a datetime object into a string, sans microseconds:

from datetime import datetime # Remove them itsy-bitsy microseconds (poof!) print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

Result: "2023-04-12 15:45:08". Microseconds? Gone.

Datetime formatting basics: strftime and isoformat

If you've been wandering in Python's datetime world, you've surely met these two fellas - strftime and isoformat. Think of them as the bread and butter of datetime formatting - capable of transforming any datetime object into a neatly formatted string.

strftime: The classic Python date-time manipulator

strftime allows you to whip up a tidy, formatted timestamp string using format directives. The format we used earlier "%Y-%m-%d %H:%M:%S" tells Python: "Hey, I want my datetime to be YYYY-MM-DD HH:MM:SS, and you better make sure there are NO microseconds!" Just the way we like it.

isoformat: The trendy kid on the block

Meanwhile, isoformat is that newbie everyone loves. Flexible, easy to use, and even more stylish when working with Python 3.6+, which boasts of a cooler timespec argument. Trust me, timespec is the party trick to impress everyone!

Code snippets! (Or: How I learned to stop worrying and love datetime formatting)

Good ol' replace

Oust those pesky microseconds before formatting:

from datetime import datetime # Here's your datetime (without any of those pesky microseconds!) dt_without_microseconds = datetime.now().replace(microsecond=0) print(dt_without_microseconds.strftime("%Y-%m-%d %H:%M:%S")) # "Did someone mention microseconds? Nope, didn't think so."

Flexing with isoformat

isoformat has come fully-prepared (for Python 3.6 or later guys):

from datetime import datetime # Say goodbye to those extra decimals. print(datetime.now().isoformat(sep=' ', timespec='seconds')) # "Less is more, amirite?"

UTC and datetime: A match made in space!

Now, let's venture to the vast universe of UTC datetimes. When exploring this space-time realm, don't forget to layer up (without any microsecond fluff!):

from datetime import datetime, timezone # HA, no time for microseconds in space! utc_dt = datetime.now(timezone.utc).replace(microsecond=0) print(utc_dt.strftime("%Y-%m-%d %H:%M:%S%z")) # "Who's ready to launch? T-minus microseconds!"

What's the time(zone)?

If your datetime is already stagged with timezone information and you wish to omit it from your output, you can convert to UTC or another timezone using astimezone(). Or simply let the %z or %Z be (they won't sneak into your output).

Look out for sneaky bugs and weird cases

Our coding world is full of weird, wacky datetime objects just waiting to trip us up. Here's how you can stride confidently:

The curious case of the missing microseconds

Your datetime objects might sneakily be without microsecond components. Here's how you deal with them (Spoiler: they don't bite!)

# No microseconds? No worries. print(datetime(2023, 4, 12, 15, 45).strftime("%Y-%m-%d %H:%M:%S")) # "Smooth sailing ahead!"

Watch out! It's the strftime directive mix-up!

One might misplace %m with %M for months and minutes, or casually forget %y (year without century) vs %Y (year with century). Be on constant lookout, test often and check those strftime directives. They're a tricky bunch.

Python version compatibility: Keeping up with the versions

Python evolves, so does its datetime module!

Python 3.6 and above

When you have the power of isoformat, use it to all its glory:

datetime.now().isoformat(sep=' ', timespec='seconds') # "The future is now!"

Prior to Python 3.6

In the absence of a built-in timespec (yeah, it's a modern luxury), side with strftime and the good ol' replace(microsecond=0) just before the formatting showdown.