1import time
2
3start = time.time()
4print("hello")
5end = time.time()
6print(end - start)
1import time
2
3start = time.time()
4print("hello")
5end = time.time()
6print(end - start)
7
1The program below converts a datetime object containing current date and time to different string formats.
2
3Code:
4
5from datetime import datetime
6
7now = datetime.now() # current date and time
8
9year = now.strftime("%Y")
10print("year:", year)
11
12month = now.strftime("%m")
13print("month:", month)
14
15day = now.strftime("%d")
16print("day:", day)
17
18time = now.strftime("%H:%M:%S")
19print("time:", time)
20
21date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
22print("date and time:",date_time)
23
24Output after run the code:
25year: 2020
26month: 03
27day: 31
28time: 04:59:31
29date and time: 03/31/2020, 04:59:31
30
31Here, year, day, time and date_time are strings, whereas now is a datetime object.
1t = time.localtime() # Gets the local time
2current_time = time.strftime("%H:%M", t) # Gets the time in the desired format
3current_time = "The time is " + current_time
1
2from datetime import datetime
3
4timestamp = 1528797322
5date_time = datetime.fromtimestamp(timestamp)
6
7print("Date time object:", date_time)
8
9d = date_time.strftime("%m/%d/%Y, %H:%M:%S")
10print("Output 2:", d)
11
12d = date_time.strftime("%d %b, %Y")
13print("Output 3:", d)
14
15d = date_time.strftime("%d %B, %Y")
16print("Output 4:", d)
17
18d = date_time.strftime("%I%p")
19print("Output 5:", d)
20
1import time
2thistime = time.time()
3# Here's an idea!
4def CountTime():
5 while(True):
6 time.sleep(1)
7 print(thistime)
8CountTime()