Python datetime to string without microsecond component

PythonDatetimeDatetime Format

Python Problem Overview


I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane).

What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?

>>> import datetime
>>> print unicode(datetime.datetime.now())
2011-11-03 11:13:39.278026

I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution.

Edit: I should mention that I'm not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07

Solution 3 - Python

In Python 3.6:

from datetime import datetime
datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'

https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat

Solution 4 - Python

This is the way I do it. ISO format:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'

You can replace the 'T' if you don't want ISO format:

datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'

Solution 5 - Python

Yet another option:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'

By default this uses local time, if you need UTC you can use the following:

>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'

Solution 6 - Python

Keep the first 19 characters that you wanted via slicing:

>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'

Solution 7 - Python

I usually do:

import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0)  # To print now without microsecond.

# To print now:
print(now)

output:

2019-01-13 14:40:28

Solution 8 - Python

Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a "." and take only the first item, which will always work:

unicode(datetime.datetime.now()).partition('.')[0]

Solution 9 - Python

As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.

isoformat(timespec='seconds', sep=' ')

Usage:

>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'

Solution 10 - Python

We can try something like below

import datetime

date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]

Solution 11 - Python

f-string formatting

>>> import datetime
>>> print(f'{datetime.datetime.now():%Y-%m-%d %H:%M:%S}')
2021-12-01 22:10:07

Solution 12 - Python

This I use because I can understand and hence remember it better (and date time format also can be customized based on your choice) :-

import datetime
moment = datetime.datetime.now()
print("{}/{}/{} {}:{}:{}".format(moment.day, moment.month, moment.year,
                                 moment.hour, moment.minute, moment.second))

Solution 13 - Python

>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'

Solution 14 - Python

I found this to be the simplest way.

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>> 
 

Solution 15 - Python

You can also use the following method

import datetime as _dt

ts = _dt.datetime.now().timestamp()
print("TimeStamp without microseconds: ", int(ts)) #TimeStamp without microseconds:  1629275829

dt = _dt.datetime.now()
print("Date & Time without microseconds: ", str(dt)[0:-7]) #Date & Time without microseconds:  2021-08-18 13:07:09

Solution 16 - Python

Current TimeStamp without microsecond component:

timestamp = list(str(datetime.timestamp(datetime.now())).split('.'))[0]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondavidchambersView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythondavidchambersView Answer on Stackoverflow
Solution 3 - PythoncodeifView Answer on Stackoverflow
Solution 4 - PythonradtekView Answer on Stackoverflow
Solution 5 - PythonAndrew ClarkView Answer on Stackoverflow
Solution 6 - PythonSteven RumbalskiView Answer on Stackoverflow
Solution 7 - PythonAn0nView Answer on Stackoverflow
Solution 8 - PythonAustin MarshallView Answer on Stackoverflow
Solution 9 - PythoncraymichaelView Answer on Stackoverflow
Solution 10 - PythonAbhishek BajajView Answer on Stackoverflow
Solution 11 - PythoncodeyeView Answer on Stackoverflow
Solution 12 - Pythonsatyakam shashwatView Answer on Stackoverflow
Solution 13 - PythonSommelierView Answer on Stackoverflow
Solution 14 - PythonMuhammed IrfanView Answer on Stackoverflow
Solution 15 - Pythonค๓เг ŦคzєlView Answer on Stackoverflow
Solution 16 - PythonAnmar GhaziView Answer on Stackoverflow