Introduction to Python - Lesson 3 - Extras
1. Time Module
- Time in Python Docs
- Python Time Moduel in Real Python
- we will use time module only to suspend the execution of the code
- syntax:
import time
- we import the time moduletime.sleep(x)
- wherex
is the number of seconds to suspend the execution of the code
1
2
3
4
5
6
# suspend execution of the code for 2 seconds
import time
print('I will sleep for 2 seconds')
time.sleep(2)
print('hello! I am awake!')
1
2
I will sleep for 2 seconds
hello! I am awake!
2. Datetime Module
- Datetime in Python Docs
- Python Datetime Module in GeeksforGeeks
- we will use datetime module only to get the current date and time
- syntax:
import datetime
- we import the datetime moduledatetime.datetime.now()
- we get the current date and timedatetime.datetime.now().year
- we get the current yeardatetime.datetime.now().month
- we get the current monthdatetime.datetime.now().day
- we get the current daydatetime.datetime.now().hour
- we get the current hourdatetime.datetime.now().minute
- we get the current minutedatetime.datetime.now().second
- we get the current seconddatetime.datetime.today()
- we get the current date and timedatetime.date.today()
- we get the date only
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import datetime
# print today date
print(datetime.date.today())
# print current time
print(datetime.datetime.now())
# print only current time
print(datetime.datetime.now().time())
# print only current hour and minute
print(f'{datetime.datetime.now().time().hour}:{datetime.datetime.now().time().minute:0>2}')
1
2
3
4
2024-03-27
2024-03-27 21:06:52.610645
21:06:52.610717
21:06
This post is licensed under CC BY 4.0 by the author.