Reputation: 879
I'm trying to make a simple system which would get the current time and get another time after few secs, then see the difference with both of the times, so it's 2 seconds. So what I need is the other format like this > YEAR,MONTH,DAY HOUR:MIN. This is the code which I use for this purpose, but in brackets there are just an example of the format I need.
a = datetime.datetime.now( %Y, %m %d %H:%M)
time.sleep(2)
b = datetime.datetime.now( %Y, %m %d %H:%M)
print(b-a)
print(a)
print(b)
Upvotes: 0
Views: 644
Reputation: 68
I thing strftime is what you're looking for
import datetime
import time
a = datetime.datetime.now()
time.sleep(2)
b = datetime.datetime.now()
print(b-a)
print(a.strftime("%Y, %m, %d %H:%M"))
print(b.strftime("%Y, %m, %d %H:%M"))
prints
0:00:02.001719
2019, 09, 04 15:17
2019, 09, 04 15:17
For more formats, you can see strftime reference: https://www.programiz.com/python-programming/datetime/strftime.
Upvotes: 1
Reputation: 313
You can convert a datetime.datetime
instance to a string formatted to your liking using the strftime()
function. For instance, to print with your preferred formatting you could do the following:
>>> import datetime
>>> a = datetime.datetime.now()
>>> print(a.strftime("%Y, %m %d %H:%M")
2019, 09 04 17:11
Subtracting two dates will yield a datetime.timedelta
object, you can convert this to the number of seconds using the total_seconds()
function:
>>> import datetime
>>> from time import sleep
>>> a = datetime.datetime.now()
>>> sleep(2)
>>> b = datetime.datetime.now()
>>> delta = b - a
>>> print(delta.total_seconds())
2.001301
Upvotes: 1