You can replace the microseconds with 0 and use isoformat:

import pytz
from datetime import datetime
tz = pytz.timezone('Asia/Taipei')
dt = datetime.now()
loc_dt = tz.localize(dt).replace(microsecond=0)
print loc_dt.isoformat()
2015-09-17T19:12:33+08:00

If you want to keep loc_dt as is do the replacing when you output:

loc_dt = tz.localize(dt)
print loc_dt.replace(microsecond=0).isoformat()

As commented you would be better passing the tz to datetime.now:

 dt = datetime.now(tz)

The reasons are discussed in pep-0495, you might also want to add an assert to catch any bugs when doing the replace:

 ssert loc_dt.resolution >= timedelta(microsecond=0)
Answer from Padraic Cunningham on Stack Overflow
Top answer
1 of 2
18

You can replace the microseconds with 0 and use isoformat:

import pytz
from datetime import datetime
tz = pytz.timezone('Asia/Taipei')
dt = datetime.now()
loc_dt = tz.localize(dt).replace(microsecond=0)
print loc_dt.isoformat()
2015-09-17T19:12:33+08:00

If you want to keep loc_dt as is do the replacing when you output:

loc_dt = tz.localize(dt)
print loc_dt.replace(microsecond=0).isoformat()

As commented you would be better passing the tz to datetime.now:

 dt = datetime.now(tz)

The reasons are discussed in pep-0495, you might also want to add an assert to catch any bugs when doing the replace:

 ssert loc_dt.resolution >= timedelta(microsecond=0)
2 of 2
2

Since python 3.6, datetime.isoformat accepts a timespec keyword to pick a precision. This argument gives the smallest time unit you want to be included in the output:

>>> loc_dt.isoformat()
'2022-10-21T19:59:59.991999+08:00'

>>> loc_dt.isoformat(timespec='seconds')
'2022-10-21T19:59:59+08:00'

>>> loc_dt.isoformat(timespec='milliseconds')
'2022-10-21T19:59:59.991+08:00'

Notice how the time is truncated and not rounded.

You can also use timespec to remove seconds/minutes:

>>> loc_dt.isoformat(timespec='minutes')
'2022-10-21T19:59+08:00'

>>> loc_dt.isoformat(timespec='hours')
'2022-10-21T19+08:00'

This all assume you ran the following setup script beforehand:

from datetime import datetime
import pytz

tz = pytz.timezone('Asia/Taipei')
dt = datetime.now()
loc_dt = tz.localize(dt)

Also note that this works without timezone:

>>> from datetime import datetime
>>> now = datetime.now()
>>> now.isoformat(timespec='minutes')
>>> '2022-10-21T19:59'
Discussions

How do i remove milliseconds?
Well, I don't know how your objects are structured; at worst, you could just parse the result: no_milliseconds = str(obj.duration).split(".")[0] More on reddit.com
🌐 r/learnpython
6
1
June 27, 2022
PSA: As of Python 3.11, `datetime.fromisoformat` supports most ISO 8601 formats (notably the "Z" suffix)
Fucking finally. More on reddit.com
🌐 r/Python
34
290
August 28, 2023
Add timespec optional flag to datetime isoformat() to choose the precision
BPO 19475 Nosy @malemburg, @gvanrossum, @tim-one, @terryjreedy, @abalkin, @vstinner, @ezio-melotti, @berkerpeksag, @vadmium, @matrixise, @alessandrocucci Files issue19475.patch: Patchissue19475_v2.... More on github.com
🌐 github.com
94
November 1, 2013
datetime - ISO time (ISO 8601) in Python - Stack Overflow
I have a file. In Python, I would like to take its creation time, and convert it to an ISO time (ISO 8601) string while preserving the fact that it was created in the Eastern Time Zone (ET). How d... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › isoformat-method-of-datetime-class-in-python
Isoformat() Method Of Datetime Class In Python - GeeksforGeeks
October 15, 2021 - Microseconds will be excluded. microseconds: For the specified microseconds, the returned time component will have HH:MM:mmmmmm format, where mmmmmm is microseconds. Return values: This function returns the date value of a Python DateTime.date ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Convert Between Isoformat String and datetime in Python | note.nkmk.me
August 22, 2023 - For example, use replace() to remove ...romisoformat.py · To exclude milliseconds and smaller units, use the split() method to separate the string at the decimal point ., and select the first element....
🌐
Pythontic
pythontic.com › datetime › datetime › isoformat
The isoformat() method of datetime class in Python | Pythontic.com
milliseconds: If milliseconds is specified, the time component will be printed in HH:MM:SS:mmm format, where mmm is milliseconds. Microseconds will be excluded. microseconds: If microseconds is specified, the time component will be printed in HH:MM:mmmmmm format, where mmmmmm is microseconds. astimezone · attributes · combine · date · fromisoformat · fromtimestamp · datetime class in Python ·
🌐
Python
bugs.python.org › issue40076
Issue 40076: isoformat function drops microseconds part if its value is 000000 - Python tracker
March 26, 2020 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/84257
🌐
Python documentation
docs.python.org › 3 › library › datetime.html
datetime — Basic date and time types
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)¶
Find elsewhere
🌐
Runebook.dev
runebook.dev › en › docs › python › library › datetime › datetime.datetime.isoformat
Troubleshooting Python's isoformat(): Timezones, Microseconds, and strftime()
By default, isoformat() includes all available microseconds. You can use the timespec argument to specify the precision you want. Common values are 'hours', 'minutes', 'seconds', or 'milliseconds'.
🌐
Python
bugs.python.org › issue19475
Issue 19475: Add timespec optional flag to datetime isoformat() to choose the precision - Python tracker
November 1, 2013 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/63674
🌐
Reddit
reddit.com › r/learnpython › how do i remove milliseconds?
r/learnpython on Reddit: How do i remove milliseconds?
June 27, 2022 -

In my django project i need to display duration of quiz test. In my model i have two datetime fields:

create_timestamp = models.DateTimeField(auto_now_add=True)
update_timestamp = models.DateTimeField(auto_now=True)

I've made a property method to display duration:

@property
def duration(self): 
    return self.update_timestamp - self.create_timestamp

In HTML output is like this: 0:02:09.099502

I wanna get rid of milliseconds. Please help \_o_O_/

🌐
Reddit
reddit.com › r/python › psa: as of python 3.11, `datetime.fromisoformat` supports most iso 8601 formats (notably the "z" suffix)
r/Python on Reddit: PSA: As of Python 3.11, `datetime.fromisoformat` supports most ISO 8601 formats (notably the "Z" suffix)
August 28, 2023 -

In Python 3.10 and earlier, datetime.fromisoformat only supported formats outputted by datetime.isoformat. This meant that many valid ISO 8601 strings could not be parsed, including the very common "Z" suffix (e.g. 2000-01-01T00:00:00Z).

I discovered today that 3.11 supports most ISO 8601 formats. I'm thrilled: I'll no longer have to use a third-party library to ingest ISO 8601 and RFC 3339 datetimes. This was one of my biggest gripes with Python's stdlib.

It's not 100% standards compliant, but I think the exceptions are pretty reasonable:

  • Time zone offsets may have fractional seconds.

  • The T separator may be replaced by any single unicode character.

  • Ordinal dates are not currently supported.

  • Fractional hours and minutes are not supported.

https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

🌐
GitHub
github.com › python › cpython › issues › 63674
Add timespec optional flag to datetime isoformat() to choose the precision · Issue #63674 · python/cpython
November 1, 2013 - assignee = 'https://github.com/abalkin' ... = ['extension-modules', 'easy', 'type-feature'] title = 'Add timespec optional flag to datetime isoformat() to choose the precision' updated_at = <Date 2016-03-06.19:58:58.039> user = ...
Author   smontanaro
Top answer
1 of 14
1247

Local to ISO 8601:

import datetime
datetime.datetime.now().isoformat()
>>> '2024-08-01T14:38:32.499588'

UTC to ISO 8601:

import datetime
datetime.datetime.now(datetime.timezone.utc).isoformat()
>>> '2024-08-01T04:38:47.731215+00:00'

Local to ISO 8601 without microsecond:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> '2024-08-01T14:38:57'

UTC to ISO 8601 with timezone information (Python 3):

import datetime
datetime.datetime.now(datetime.timezone.utc).isoformat()
>>> '2024-08-01T04:39:06.274874+00:00'

Local to ISO 8601 with timezone information (Python 3):

import datetime
datetime.datetime.now().astimezone().isoformat()
>>> '2024-08-01T14:39:16.698776+10:00'

Local to ISO 8601 with local timezone information without microsecond (Python 3):

import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> '2024-08-01T14:39:28+10:00'

Notice there is a bug when using astimezone() on utcnow(). This gives an incorrect result:

datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result, do not use.

.utcnow() is deprecated, use .now(datetime.timezome.utc) instead.

For Python 2, see and use pytz.

2 of 14
139

ISO 8601 allows a compact representation with no separators except for the T, so I like to use this one-liner to get a quick timestamp string:

>>> datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'

If you don't need the microseconds, just leave out the .%f part:

>>> datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'

For local time:

>>> datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-5))).strftime("%Y-%m-%dT%H:%M:%S%:z")
'2018-09-05T14:09:03-05:00'

In general, I recommend you leave the punctuation in. RFC 3339 recommends that style because if everyone uses punctuation, there isn't a risk of things like multiple ISO 8601 strings being sorted in groups on their punctuation. So the one liner for a compliant string would be:

>>> datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
'2018-09-05T14:09:03Z'
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to remove milliseconds from python datetime
5 Best Ways to Remove Milliseconds from Python datetime - Be on the Right Side of Change
February 28, 2024 - The code creates a string representation of a datetime, then splits and removes the milliseconds before reconverting it back into a datetime object without milliseconds.
🌐
Statology
statology.org › home › how to work with date and time in iso format in python
How to Work with Date and Time in ISO Format in Python
August 16, 2024 - The isoformat() method automatically includes microseconds if present. To omit them, you can use string slicing: iso_string_without_microseconds = now.isoformat().split('.')[0] print(f"Without microseconds: {iso_string_without_microseconds}")
🌐
w3resource
w3resource.com › python-exercises › date-time-exercise › python-date-time-exercise-17.php
Python: Drop microseconds from datetime - w3resource
July 22, 2025 - It retrieves the current date and time using "datetime.datetime.today()". Then, it removes the microseconds from the time component using the "replace()" method with the argument 'microsecond=0'. Finally it prints the current date and time with ...