·

Difference between time and datetime in python

Published at 2024-05-09 19:55:13Viewed 330 times
Professional article
Please reprint with source link

Manipulating time is common during development. Python provides two packages from time, which are datetime and time. We will discuss the difference between the basic functions of these two packages.

1. time :

To get the current local time, first you need to run time.time() to get the current timestamp.

import time

#Get the current timestamp
time.time()
#output: 1715254313.7382145

Then you need to format the resulting timestamp to get your desirable time format, e.g. %Y-%m-%d %H:%M:%S.

time.localtime(time.time())
#output: time.struct_time(tm_year=2024, tm_mon=5, tm_mday=9, tm_hour=19, tm_min=34, tm_sec=54, tm_wday=3, tm_yday=130, tm_isdst=0)
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
#output: '2024-05-09 19:37:54'

It takes 5.5 seconds to run time.time() 100000000 times.

start = time.time() 
for _ in range(100000000): 
    pass 
end = time.time()
print("%.2f seconds"%(end-start))
#output: 5.50 seconds

2. datetime :

To get the current local time, first you need to run datetime.datetime.now(), which outputs the current datetime object.

import datetime

datetime.datetime.now()
#output: datetime.datetime(2024, 5, 9, 19, 43, 9, 36941)

Then you could transform the resulting datetime object to string in your desirable format, e.g. %Y-%m-%d %H:%M:%S.

datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#output: '2024-05-09 19:44:48'

It takes 5 seconds to run datetime.datetime.now() 100000000 times.

start = datetime.datetime.now()
while True:
    for i in range(100000000):
        pass
    break
end = datetime.datetime.now()
print(str((end-start).seconds)+"seconds")
#output: 5 seconds


0 人喜欢

Comments

There is no comment, let's add the first one.

弦圈热门内容

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved