how to use strftime in python code example
Example 1: python time format
The program below converts a datetime object containing current date and time to different string formats.
Code:
from datetime import datetime
now = datetime.now()
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
Output after run the code:
year: 2020
month: 03
day: 31
time: 04:59:31
date and time: 03/31/2020, 04:59:31
Here, year, day, time and date_time are strings, whereas now is a datetime object.
Example 2: time.strftime("%H:%M:%S") in python
import time
t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
t = time.mktime(t)
print time.strftime("%b %d %Y %H:%M:%S", time.gmtime(t))
Example 3: time.strftime("%H:%M:%S") in python
time.strftime(format[, t])