Python datetime to string without microsecond component
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:
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:
Flexing with isoformat
isoformat
has come fully-prepared (for Python 3.6 or later guys):
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!):
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!)
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:
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.
Was this article helpful?