August 11, 2018
Get current datetime without milliseconds in Python
Introduction
In Python, the datetime module can be used to get date and time. This is good but there is something annoying: the milliseconds or the fraction that gets printed by default. How can we get rid of that ? There are a couple of ways to do the trick.
Let us see…
Example code
The following code snippet shows the default behavior…
1 2 3 4 5 6 7 8 9 |
# Import datetime module import datetime # Get current date and time dt = datetime.datetime.now() # This is going to print someting like: # 2018-08-11 16:23:45.524765 print(dt) |
We can change the default behavior by formatting the date time string as follows…
1 2 3 4 5 6 7 8 9 10 11 12 |
# Import datetime module import datetime # Get current date and time dt = datetime.datetime.now() # Format datetime string x = dt.strftime("%Y-%m-%d %H:%M:%S") # This is going to print something like: # 2018-08-11 16:25:05 print(x) |
The replace function can do the job as well…
1 2 3 4 5 6 7 8 9 |
# Import datetime module import datetime # Get current date and time dt = datetime.datetime.now() # This is going to remove the milliseconds x = dt.replace(microsecond=0) print(x) |
Splitting the string using the dot as a delimiter works perfectly…
1 2 3 4 5 6 7 8 9 |
# Import datetime module import datetime # Get current date and time dt = datetime.datetime.now() # Using the split built in function x = str(dt).split('.')[0] print(x) |
And finally something fancy like regular expressions…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Import datetime module import datetime # Regular expressions import re # Get current date and time dt = datetime.datetime.now() # Match datetime string then dot then milliseconds mat = re.match(r'(.+)\.(.+)', str(dt), re.M|re.I) # First group is the datetime string without # milliseconds print(mat.group(1)) |
That was it for today. I hope it was useful. Thanks for visiting.
More from my site
3 Comments
import datetime
def time():
dt = datetime.datetime.now()
print str(dt)[0:19]
>>>2019-11-29 20:52:33
great post!
import datetime as _dt
ts = _dt.datetime.now().timestamp()
print(“TimeStamp without microseconds: “, int(ts))
dt = _dt.datetime.now()
print(“Date & Time without microseconds: “, str(dt)[0:-7])