How to get the current date and time in Python

Today we are going to share how to get the current date and time in Python. If you are a python beginner and want to start learning the python programming, then keep your close attention in this tutorial as I am going to share how to get the current date and time in Python.

How to get the current date and time in Python

Copy the below python program and execute it with the help of python compiler.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

importdatetime

now=datetime.datetime.now()

print

print"Current date and time using str method of datetime object:"

printstr(now)

print

print"Current date and time using instance attributes:"

print"Current year: %d"%now.year

print"Current month: %d"%now.month

print"Current day: %d"%now.day

print"Current hour: %d"%now.hour

print"Current minute: %d"%now.minute

print"Current second: %d"%now.second

print"Current microsecond: %d"%now.microsecond

print

print"Current date and time using strftime:"

printnow.strftime("%Y-%m-%d %H:%M")

Output

Current date and time using str method of datetime object: 2013-02-17 16:02:49.338517 Current date and time using instance attributes: Current year: 2013 Current month: 2 Current day: 17 Current hour: 16 Current minute: 2 Current second: 49 Current microsecond: 338517 Current date and time using strftime: 2013-02-17 16:02

Subscribe my updates via Email

We use cookies to ensure that we give you the best experience and deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.OkPrivacy policy