3

I need date-time string in ISO 8601 without any microseconds.

Like:

2015-01-05T11:26:00-03:00

I use:

from pytz import timezone
from datetime import datetime
timezone(settings.TIME_ZONE).localize(datetime.now()).isoformat()

But it returns:

'2015-01-28T17:49:39.711725-03:00'

How to fix that?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Leon
  • 6,316
  • 19
  • 62
  • 97
  • 1
    to get the current localized time, use `datetime.now(timezone(settings.TIME_ZONE))`. Do not use `.localize(naive_local_time)` -- local time may be ambiguous e.g., during end-of-DST transitions. `now(timezone(settings.TIME_ZONE))` always works because it uses `fromutc()` internally while `.localize()` may return a wrong result for ambiguous or non-existent local time. – jfs Jan 28 '15 at 15:56
  • related: [Formatting microseconds to two decimal places (in fact converting microseconds into tens of microseconds)](https://stackoverflow.com/q/26586943/4279) – jfs Apr 11 '18 at 13:50

1 Answers1

11

Set microsecond as 0:

t = timezone(settings.TIME_ZONE).localize(datetime.now()).replace(microsecond=0)
t.isoformat()

datetime.datetime.replace(...) will return a new datetime object with specified attribute modified.

falsetru
  • 357,413
  • 63
  • 732
  • 636