xxxxxxxxxx
# 10 July 2021, 10:54:27AM
datetime.strftime("%-d %B %Y, %I:%M:%S%p")
xxxxxxxxxx
import datetime
# Get the current datetime object
now = datetime.datetime.now()
# Format the datetime object as a string
formatted_datetime = now.strftime("%Y-%m-%d %H:%M:%S")
# Print the formatted datetime
print(formatted_datetime)
xxxxxxxxxx
import time
time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
datetime format codes
xxxxxxxxxx
Code Description and Ranges Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%z UTC offset +0100
%Z Timezone CST
%j Day number of year 001-366 365
%U Week number of year, Sunday as
the first day of week, 00-53 52
%W Week number of year, Monday as
the first day of week, 00-53 52
%c Local version of date and time Mon Dec 31 17:41:00 2018
%C Century 20
%x Local version of date 12/31/18
%X Local version of time 17:41:00
%% A % character %
%G ISO 8601 year 2018
%u ISO 8601 weekday (1-7) 1
%V ISO 8601 weeknumber (01-53) 01
xxxxxxxxxx
import datetime
# Get current time
current_time = datetime.datetime.now()
# Format time as HH:MM:SS
formatted_time = current_time.strftime("%H:%M:%S")
print(formatted_time)
xxxxxxxxxx
# Python program to demonstrate strftime() function
from datetime import datetime as date
# Getting current date and time
now = date.now()
print("Without formatting", now)
# Example 1
s = now.strftime("%A %m %-Y")
print('\nExample 1:', s)
# Example 2
s = now.strftime("%a %-m %y")
print('\nExample 2:', s)
# Example 3
s = now.strftime("%-I %p %S")
print('\nExample 3:', s)
# Example 4
s = now.strftime("%H:%M:%S")
print('\nExample 4:', s)