Python: How to convert datetime format?

Python: How to convert datetime format?

In this article, How to convert datetime format in python?. Date formatting is one of the most important tasks that you will face as a programmer. Different regions around the world have different ways of representing dates/times, your goal as a programmer is to present the date values in a way that is readable to the users.

Some example of datetime format in python below:-

 

t = datetime.time(2, 10, 20, 13)

Output

02:10:20.000013

 

print('Minutes:', t.minute)
print('Seconds:', t.second)
print('Microsecond:', t.microsecond)

Output

Minutes: 20
Seconds: 40
Microseconds: 30

 

print('hour:', t.hour)

Output

hour: 1

 

today method

 

import datetime

today = datetime.date.today()

print(today)


Output

2020-12-19

 

You can display year, month, and day using the date class:

 

print('Year:', today.year)
print('Month:', today.month)
print('Day :', today.day)

Year: 2020
Month: 12
Day : 19

 

Now you call the ctime method to print the date in another format:

 

print('ctime:', today.ctime())

Output

ctime: Sat Dec 19 00:00:00 2020

 

Converting Dates to Strings with strftime

 

using the strftime method

 

time.strftime(format, t)

 

import datetime

x = datetime.datetime(2020, 12, 19, 14, 50, 40)

print(x.strftime("%b %d %Y %H:%M:%S"))

Output

Dec 19 2020 14:50:40

 

import datetime

x = datetime.datetime(2020, 12, 19)

print(x.strftime('%b/%d/%Y'))

Output

Dec/19/2020

 

print(x.strftime('%B'))

Output

December

 

print(x.strftime('%y'))

Output

20

 

print(x.strftime('%Y'))

Output

2020

 

Converting Strings to Dates with strptime

 

from datetime import datetime

str = '12-19-20'
date_object = datetime.strptime(str, '%m-%d-%y')

print(date_object)

Output

2020-12-19 00:00:00

 

Use strftime

 

date_time = datetime.now()
print(date_time)
print(datetime.strftime(date_time, '%Y-%m-%d %H:%M:%S,%f'))

2020-12-19 11:20:05.627610
2020-12-19 11:20:05,627610

 

import datetime

x = datetime.datetime(2020, 12, 19)

print(x.strftime("%b %d %Y %H:%M:%S"))

Output


Dec 19 2020 00:00:00

 

 

2021-10-03