Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22855

IslandT: Python Datetime Module

$
0
0

Python datetime module allows you to create an datetime object or get the date of a particular day. Let me create a few examples to demonstrate to you how to use the methods of this DateTime module.

Find the present date and day, month, etc.

import datetime

current_date = datetime.datetime.now()
print(current_date.strftime("%A")) #Weekday
print(current_date.strftime("%w")) #Weekday as a number 0-6, 0 is Sunday
print(current_date.strftime("%d")) #Day of month 
print(current_date.strftime("%B")) #Month name
print(current_date.strftime("%m")) #Month as a number 01-12
print(current_date.strftime("%Y")) #Year
print(current_date.strftime("%H")) #Hour from 00 - 23
print(current_date.strftime("%p")) #AM/PM
print(current_date.strftime("%M")) #Minute
print(current_date.strftime("%S")) #Second
print(current_date.strftime("%C")) #Century
print(current_date.strftime("%j")) #Day number of year 

As you can see that the strftime method above will accept a string parameter which is uses to retrieve the value of a particular element within that particular date, such as a weekday.

Below are the outcomes of the above program.

Wednesday
3
05
October
10
2022
20
PM
20
26
20
278

Another method to use the datetime object is to create your datetime object as follows:

current_time = datetime.datetime(2022, 10, 5)

There are still lots of fantastic Python modules that I will leave to you to explore and thus I will conclude the Module area of the Python programming language.

In the coming article, I will start to create a python program thus letting us learn together how to write Python code.


Viewing all articles
Browse latest Browse all 22855

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>