banner

© 2004-20 ict4u.net

String to Date

Useful bits of code to return the current date
This code will show you how selct parts of the date and how to print the date in a formatted manner

#Author: A Knifton
#Date: 20 Mar 2018
#Purpose: handling Date & Time

from datetime import datetime
# get the full date and time into one variable
fullDateTime = datetime.today()

# use the today method to return various parts of the date
cYear = datetime.today().year
cMonth = datetime.today().month
cDay = datetime.today().day
cTime = datetime.today().time()

#output various parts to demo how it works
print(f"The current year is {cYear}\nThe month is {cMonth}\nThe day  is {cDay}\nThe time  is {cTime}\n\n")

print(f'Current date and time {fullDateTime}')

# now use strftime to format the date object to display in a way that is useful to the user
# see a full list of codes here: http://strftime.org/
print(f"Reformatted: {fullDateTime.strftime('%A, %d %B %Y')}")