Reputation: 3482
Currently I am logging stuff and I am using my own formatter with a custom formatTime()
:
def formatTime(self, _record, _datefmt):
t = datetime.datetime.now()
return t.strftime('%Y-%m-%d %H:%M:%S.%f')
My issue is that the microseconds, %f
, are six digits. Is there anyway to spit out less digits, like the first three digits of the microseconds?
Upvotes: 103
Views: 192670
Reputation: 354
Could create a function and pass through datetime
from datetime import datetime as dt
(lambda t_dt: t_dt.strftime(f"{'%d.%m.%Y %H:%M:'}{t_dt.second+round(t_dt.microsecond/1e6,3)}"))(dt.now())
Upvotes: 0
Reputation: 367
I was looking for the format: '2023-10-19T18:12:44.884Z' After reading suggestions on the page, I was able to get what I wanted in one line:
f"{now.strftime('%Y-%m-%dT%H:%M:%S')}.{str(now.microsecond)[:3]}Z"
Upvotes: 1
Reputation: 382
steveha already said truncating. That will round you down. But if you want to round to the nearest digit, the way to round numbers in general is to add 5 to the place of decimals you would be cutting off, before doing the truncating. So for example to round 12.3456 to 3 places of decimals, add 0.0005; that gives you 12.3461 which you then truncate to 3 characters after the point, giving you 12.346.
The question is, how to add 5 to the next place of decimals -- correctly. So you can't just consider the microseconds, if you round up .9995 seconds when it's just before midnight on New Year's eve, the carry might go all the way up to the year!
But you can use a timedelta. Then the time calculation is correct and you can just truncate to get your correctly-rounded value.
To round to 3 places of decimals in seconds, you want to add 0.0005 seconds = 500 microseconds. Here are 3 examples: first, round 0.1234 seconds to 0.123, then round 0.1235 seconds to 0.124, then have the carry propagate all the way when you should be kissing someone to wish them happy new year and instead you're doing Python:
>>> r = datetime.timedelta(microseconds=500)
>>> t = datetime.datetime(2023,1,2,3,45,6,123456)
>>> (t+r).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
'2023-01-02 03:45:06.123'
>>> t = datetime.datetime(2023,1,2,3,45,6,123556)
>>> (t+r).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
'2023-01-02 03:45:06.124'
>>> t = datetime.datetime(2023,12,31,23,59,59,999500)
>>> (t+r).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
'2024-01-01 00:00:00.000'
Upvotes: 2
Reputation: 1
Adding my two cents here as this method will allow you to write your microsecond format as you would a float in c-style. It takes advantage that they both use %f
.
import datetime
import re
def format_datetime(date, format):
"""Format a ``datetime`` object with microsecond precision.
Pass your microsecond as you would format a c-string float.
e.g "%.3f"
Args:
date (datetime.datetime): You input ``datetime`` obj.
format (str): Your strftime format string.
Returns:
str: Your formatted datetime string.
"""
# We need to check if formatted_str contains "%.xf" (x = a number)
float_format = r"(%\.\d+f)"
has_float_format = re.search(float_format, format)
if has_float_format:
# make microseconds be decimal place. Might be a better way to do this
microseconds = date.microsecond
while int(microseconds): # quit once it's 0
microseconds /= 10
ms_str = has_float_format.group(1) % microseconds
format = re.sub(float_format, ms_str[2:], format)
return date.strftime(format)
print(datetime.datetime.now(), "%H:%M:%S.%.3f")
# '17:58:54.424'
Upvotes: 0
Reputation: 1178
You can subtract the current datetime from the microseconds.
d = datetime.datetime.now()
current_time = d - datetime.timedelta(microseconds=d.microsecond)
This will turn 2021-05-14 16:11:21.916229
into 2021-05-14 16:11:21
Upvotes: 4
Reputation: 885
As of Python 3.6 the language has this feature built in:
def format_time():
t = datetime.datetime.now()
s = t.isoformat(timespec='milliseconds')
return s
Upvotes: 68
Reputation: 76755
The simplest way would be to use slicing to just chop off the last three digits of the microseconds:
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3]
I strongly recommend just chopping. I once wrote some logging code that rounded the timestamps rather than chopping, and I found it actually kind of confusing when the rounding changed the last digit. There was timed code that stopped running at a certain timestamp yet there were log events with that timestamp due to the rounding. Simpler and more predictable to just chop.
If you want to actually round the number rather than just chopping, it's a little more work but not horrible:
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
head = s[:-7] # everything up to the '.'
tail = s[-7:] # the '.' and the 6 digits after it
f = float(tail)
temp = "{:.03f}".format(f) # for Python 2.x: temp = "%.3f" % f
new_tail = temp[1:] # temp[0] is always '0'; get rid of it
return head + new_tail
Obviously you can simplify the above with fewer variables; I just wanted it to be very easy to follow.
Upvotes: 137
Reputation: 395
If once want to get the day of the week (i.e, 'Sunday)' along with the result, then by slicing '[:-3]' will not work. At that time you may go with,
dt = datetime.datetime.now()
print("{}.{:03d} {}".format(dt.strftime('%Y-%m-%d %I:%M:%S'), dt.microsecond//1000, dt.strftime("%A")))
#Output: '2019-05-05 03:11:22.211 Sunday'
%H - for 24 Hour format
%I - for 12 Hour format
Thanks,
Upvotes: 0
Reputation: 51
An easy solution that should work in all cases:
def format_time():
t = datetime.datetime.now()
if t.microsecond % 1000 >= 500: # check if there will be rounding up
t = t + datetime.timedelta(milliseconds=1) # manually round up
return t.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
Basically you do manual rounding on the date object itself first, then you can safely trim the microseconds.
Upvotes: 5
Reputation: 6371
Edit: As some pointed out in the comments below, the rounding of this solution (and the one above) introduces problems when the microsecond value reaches 999500, as 999.5 is rounded to 1000 (overflow).
Short of reimplementing strftime to support the format we want (the potential overflow caused by the rounding would need to be propagated up to seconds, then minutes, etc.), it is much simpler to just truncate to the first 3 digits as outlined in the accepted answer, or using something like:
'{:03}'.format(int(999999/1000))
-- Original answer preserved below --
In my case, I was trying to format a datestamp with milliseconds formatted as 'ddd'. The solution I ended up using to get milliseconds was to use the microsecond
attribute of the datetime
object, divide it by 1000.0, pad it with zeros if necessary, and round it with format. It looks like this:
'{:03.0f}'.format(datetime.now().microsecond / 1000.0)
# Produces: '033', '499', etc.
Upvotes: 4
Reputation: 15
Fixing the proposed solution based on Pablojim Comments:
from datetime import datetime
dt = datetime.now()
dt_round_microsec = round(dt.microsecond/1000) #number of zeroes to round
dt = dt.replace(microsecond=dt_round_microsec)
Upvotes: 0
Reputation: 2707
Here is my solution using regexp:
import re
# Capture 6 digits after dot in a group.
regexp = re.compile(r'\.(\d{6})')
def to_splunk_iso(dt):
"""Converts the datetime object to Splunk isoformat string."""
# 6-digits string.
microseconds = regexp.search(dt.isoformat()).group(1)
return regexp.sub('.%d' % round(float(microseconds) / 1000), dt.isoformat())
Upvotes: 2
Reputation: 386
This method should always return a timestamp that looks exactly like this (with or without the timezone depending on whether the input dt
object contains one):
2016-08-05T18:18:54.776+0000
It takes a datetime
object as input (which you can produce with datetime.datetime.now()
). To get the time zone like in my example output you'll need to import pytz
and pass datetime.datetime.now(pytz.utc)
.
import pytz, datetime
time_format(datetime.datetime.now(pytz.utc))
def time_format(dt):
return "%s:%.3f%s" % (
dt.strftime('%Y-%m-%dT%H:%M'),
float("%.3f" % (dt.second + dt.microsecond / 1e6)),
dt.strftime('%z')
)
I noticed that some of the other methods above would omit the trailing zero if there was one (e.g. 0.870
became 0.87
) and this was causing problems for the parser I was feeding these timestamps into. This method does not have that problem.
Upvotes: 11
Reputation: 6059
This method allows flexible precision and will consume the entire microsecond value if you specify too great a precision.
def formatTime(self, _record, _datefmt, precision=3):
dt = datetime.datetime.now()
us = str(dt.microsecond)
f = us[:precision] if len(us) > precision else us
return "%d-%d-%d %d:%d:%d.%d" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, int(f))
This method implements rounding to 3 decimal places:
import datetime
from decimal import *
def formatTime(self, _record, _datefmt, precision='0.001'):
dt = datetime.datetime.now()
seconds = float("%d.%d" % (dt.second, dt.microsecond))
return "%d-%d-%d %d:%d:%s" % (dt.year, dt.month, dt.day, dt.hour, dt.minute,
float(Decimal(seconds).quantize(Decimal(precision), rounding=ROUND_HALF_UP)))
I avoided using the strftime
method purposely because I would prefer not to modify a fully serialized datetime object without revalidating it. This way also shows the date internals in case you want to modify it further.
In the rounding example, note that the precision is string-based for the Decimal
module.
Upvotes: 1