Python Datetime

python-strftime-method-ipcisco

To work with dates in python, we need to import a module to our code. This python date module is python datetime module.

 

With the below code, we can print the current time with a python code.

 

import datetime
a = datetime.datetime.now()
print(a)

 

The output of this code will be the time of now which contains year, month, day, hour, minute, second, and microsecond values of the current time.

 

2021-11-16 23:16:5.108448

python-datetime-ipcisco

There are different methods used with datetime module of python. Below, you will find some of the examples on these methods.

 


 

How to Create A Date Object?

 

In Python to create a date object, we use datetime module. Firstly, we import this module and then, we use three key parameters of this method to create this date object. Below, there is an example for this.

 

import datetime
a = datetime.datetime(2050, 5, 10)
print(a)

 

The output of this code will be:

 

2050-05-10 00:00:00

 

 


 

How to use strftime method?

 

In Python there is an important method used with time named python strftime method. With this method, we can format date objects into readable format. This method takes one parameter and the related parameters are given below with their meanings.

 

Let’s think about the time of now. Here, below letters will give us the below outputs about the time.

 

python-strftime-method-ipcisco

%a Day name (short) Tue

%A Day name  Tuesday

%w Day Number (Sunday=0) 2

%d Day of month (01-31) 16

%b Month name (short) Nov

%B Month name  November

%m Month number  11

%y Year (short)  21

%Y Year   2021

%H Hour    23

%I Hour (00-12)  11

%p AM/PM   PM

%M Minute    16

%S Second    05

%f Microsecond   254765

%Z Timezone  CST

%j Day number  320

%W Week number  46

%C Century   20

%x Local version of date 11/16/21

%X Local version of time 23:16:00

%c Local date and time Mon Dec 31 23:16:00 2021

 

Let’s do an example with strftime method of python.

 

import datetime
x = datetime.datetime.now()
print(x.strftime("%a"))
print(x.strftime("%d"))
print(x.strftime("%B"))
print(x.strftime("%j"))
print(x.strftime("%W"))

 

The output of this python strftime method code will be:

 

Tue
16
November
320
46

 

python-strftime-method-ipcisco.com

 

In this python time lesson, we have learned how to work with times and date in python programming. You can use these methods and python datetime module in your various projects.

Back to: Python Programming Course

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand
Latest Blog Posts