strftime()
Date and time formatting is important.
strftime – Method to create a string from a datetime.
It takes a datetime, returns a string.
>>> import datetime >>> now = datetime.datetime.now() >> now datetime.datetime(2017, 4, 17, 17, 53, 12, 223121) >>> # This doesn't look good.....
strftime will help make our output datetimes look pretty.
>>> now.strftime('%B %d')
'April 17'
>>> now.strftime('%m/%d/%y')
'04/17/17'
You don’t have to memorize all these directive symbols.
Get them from their sources:
strptime()
strptime – Method to create a datetime from a string according to a format string.
It takes a string, returns a datetime.
>>> birthday = datetime.datetime.strptime('2015-04-21', '%Y-%m-%d') >>> birthday datetime.datetime(2015, 4, 21, 0, 0)
>>> birthday_party = datetime.datetime.strptime('2015-04-21 12:00', '%Y-%m-%d %H:%M')
>>> birthday_party
datetime.datetime(2015, 4, 21, 12, 0)
Remember
strftime is a string from time. strptime is a string parsed into time.
Exercise: from & to
Create a function named to_string that takes a datetime and gives back a string in the format "24 September 2012".
Then, create a new function named from_string that takes two arguments: a date as a string and an strftime-compatible format string, and returns a datetime created from them.
## Examples
# to_string(datetime_object) => "24 September 2012"
# from_string("09/24/12 18:30", "%m/%d/%y %H:%M") => datetime
def to_string(my_datetime):
return my_datetime.strftime('%d %B %Y')
def from_string(datetime_str, datetime_format):
return datetime.datetime.strptime(datetime_str, datetime_format)