Post

Introduction to Python - Lesson 3 - Extras

1. Time Module

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 module
    • datetime.datetime.now() - we get the current date and time
    • datetime.datetime.now().year - we get the current year
    • datetime.datetime.now().month - we get the current month
    • datetime.datetime.now().day - we get the current day
    • datetime.datetime.now().hour - we get the current hour
    • datetime.datetime.now().minute - we get the current minute
    • datetime.datetime.now().second - we get the current second
    • datetime.datetime.today() - we get the current date and time
    • datetime.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.