13

Given the following datetime:

d = datetime.datetime(2018, 10, 9, 8, 19, 16, 999578, tzinfo=dateutil.tz.tzoffset(None, 7200))

d.isoformat() results in the string:

'2018-10-09T08:19:16.999578+02:00'

How can I get a string with milliseconds instead of microseconds:

'2018-10-09T08:19:16.999+02:00'

strftime() will not work here: %z returns 0200 istead of 02:00 and has only %f to get microseconds, there is no placeholder for milliseconds.

3
  • Possible duplicate of Using %f with strftime() in Python to get microseconds Commented Oct 23, 2018 at 8:16
  • strftime(): %z returns 0200 istead of 02:00 and has only %f to get microseconds, no placeholder for milliseconds. Commented Oct 23, 2018 at 8:22
  • formatting time data in datetime object to strings is still using str.format(), if you can get microseconds & millisecs from datetime object you can format the strings representations in any way str.format can do. strftime() is exactly the provided method for that. Commented Oct 23, 2018 at 8:57

3 Answers 3

16

If timezone without colon is ok, you can use

d = datetime.datetime(2018, 10, 9, 8, 19, 16, 999578, 
                      tzinfo=dateutil.tz.tzoffset(None, 7200))
s = d.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + d.strftime('%z')
# '2018-10-09T08:19:16.999+0200'

For colon, you need to split the timezone and add it there yourself. %z does not produce Z either for UTC.


And Python 3.6 supports timespec='milliseconds' so you should shim this:

try:
    datetime.datetime.now().isoformat(timespec='milliseconds')
    def milliseconds_timestamp(d):
        return d.isoformat(timespec='milliseconds')

except TypeError:
    def milliseconds_timestamp(d):
        z = d.strftime('%z')
        z = z[:3] + ':' + z[3:]
        return d.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + z

Given the latter definition in Python 3.6,

>>> milliseconds_timestamp(d) == d.isoformat(timespec='milliseconds')
True

with

>>> milliseconds_timestamp(d)
'2018-10-09T08:19:16.999+02:00'
Sign up to request clarification or add additional context in comments.

2 Comments

Colon is important and it has to run with python 3.5.
@cytrinox then my latter excerpt
0

on 3.10 (maybe earlier, too), you can do it on a one-liner

>>> now = datetime.datetime.now()
>>> tz = datetime.timezone(datetime.timedelta(hours=-6), name="CST")
>>> now_tz = now.replace(tzinfo=tz)
>>> now_tz.isoformat("#","milliseconds")
'2023-03-02#11:02:07.592-06:00'

Comments

0
import datetime

now = datetime.datetime.now()

tz = datetime.timezone(datetime.timedelta(hours=-6), name="CST")

now_tz = now.replace(tzinfo=tz)

now_tz.isoformat("#", "milliseconds")

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.