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…

We can change the default behavior by formatting the date time string as follows…

The replace function can do the job as well…

Splitting the string using the dot as a delimiter works perfectly…

And finally something fancy like regular expressions…

That was it for today. I hope it was useful. Thanks for visiting.

Tags:
3 Comments

Add a Comment

Your email address will not be published. Required fields are marked *