Saturday, June 20, 2020

Date Time

Sometimes it becomes very important to use date and/or time in our code. In this session, let's try to see how we can get current date time and convert it into different formats. For this we need to import datetime module.
import datetime

current_date_time = datetime.datetime.now()

print(current_date_time)


2020-06-21 14:52:14.623809
Let's now try to get today's date or say only current day/month/year.
import datetime

today = datetime.date.today()

print("Today's Date:", today)
print("Today's day:", today.day)
print("Today's month:", today.month)
print("Today's year:", today.year)

Today's Date: 2020-06-21
Today's day: 21
Today's month: 6
Today's year: 2020
Now, let's try to convert it into different format.
import datetime

today = datetime.date.today()

print("Date in dd/mm/yyyy: ", today.strftime("%d/%m/%Y"))
print("Date in mmm dd, yyyy: ", today.strftime("%b %d, %Y"))

Date in dd/mm/yyyy:  21/06/2020
Date in mmm dd, yyyy:  Jun 21, 2020
Similarly, we can get and format time
import datetime

current_date_time = datetime.datetime.now()

print('Current Time (0-24):', current_date_time.strftime("%H:%M:%S"))
print('Current Time (0-12):', current_date_time.strftime("%I:%M:%S %p"))
print('Current Hour (0-24):', current_date_time.strftime("%H"))
print('Current Hour (0-12):', current_date_time.strftime("%I %p"))
print('Current Minute:', current_date_time.strftime("%M"))
print('Current Second:', current_date_time.strftime("%S"))


Current Time (0-24): 02:54:25
Current Time (0-12): 02:54:25 PM
Current Hour (0-24): 14
Current Hour (0-12): 14 PM
Current Minute: 54
Current Second: 25
Here are some formats that can be used
Format Code Description Example
%Y YYYY 2020
%y yy 20
%m mm 06
%b mmm Jun
%B mmmm June
%d dd 21
%H 0-24 14
%i 0-12 02
%p AM/PM PM
%M Minute 55
%S Seconds 32

No comments:

Post a Comment