You can use datetime.replace() method -
>>> d = datetime.datetime.today().replace(microsecond=0)
>>> d
datetime.datetime(2015, 7, 18, 9, 50, 20)
Answer from Anand S Kumar on Stack Overflowsimple way to drop milliseconds from python datetime.datetime object - Stack Overflow
Python datetime to string without microsecond component - Stack Overflow
How do i remove milliseconds?
python - How to trim time string to specific format? - Stack Overflow
If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:
>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'
See the documentation of datetime.strftime() for an explanation of the % directives.
Starting from Python 3.6, the isoformat() method is flexible enough to also produce this format:
datetime.datetime.now().isoformat(sep=" ", timespec="seconds")
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07
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_timestampIn HTML output is like this: 0:02:09.099502
I wanna get rid of milliseconds. Please help \_o_O_/
Are you okay with lower precision?
Apply simple string operation to get rid of 3 extra digits and pass it to datetime.datetime.strptime.
import datetime
t = '2022-05-09 08:02:18.106869456 +0000 UTC'
t2 = t[:26] + t[29:] # made some assumptions about time string format
datetime.datetime.strptime(t2, '%Y-%m-%d %H:%M:%S.%f %z %Z')
# expected output: datetime.datetime(2022, 5, 9, 8, 2, 18, 106869, tzinfo=datetime.timezone(datetime.timedelta(0), 'UTC'))
Pro You can use Regex to split each part of the string using this regex
import re
regex = r"""(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})\s(?P<hour>[0-9]{2}):(?P<min>[0-9]{2}):(?P<sec>[0-9]{2}).(?P<micro>\d*)\s(?P<diff>[\+\-]\d+)\s(?
P<time_zone>\w+)"""
d = re.search(regex,'2022-05-09 08:02:18.106869456 +0000 UTC').groupdict()
print(d)
Then You can take what you want from the string
print:
{'year': '2022', 'month': '05', 'day': '09', 'hour': '08', 'min': '02',
'sec': '18', 'micro': '106869456', 'diff': '+0000', 'time_zone': 'UTC'}
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.
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
I think this is what you're looking for...
>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy
>>> dt
datetime.datetime(2011, 3, 29, 0, 0)
But if you really don't care about the time aspect of things, then you should really only be passing around date objects...
>>> d_truncated = datetime.date(dt.year, dt.month, dt.day)
>>> d_truncated
datetime.date(2011, 3, 29)
Use a date not a datetime if you dont care about the time.
>>> now = datetime.now()
>>> now.date()
datetime.date(2011, 3, 29)
You can update a datetime like this:
>>> now.replace(minute=0, hour=0, second=0, microsecond=0)
datetime.datetime(2011, 3, 29, 0, 0)
dtwithoutseconds = dt.replace(second=0, microsecond=0)
http://docs.python.org/library/datetime.html#datetime.datetime.replace
I know it's quite old question, but I haven't found around any really complete answer so far.
There's no need to create a datetime object first and subsequently manipulate it.
dt = datetime.now().replace(second=0, microsecond=0)
will return the desired object
To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'
Or shorter:
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]
'2022-09-24 10:18:32.926'
See the Python docs for more "%" format codes and the strftime(3) man page for the full list.
With Python 3.6+, you can set isoformat's timespec:
>>> from datetime import datetime
>>> datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
'2019-05-10 09:08:53.155'