Get startedGet started for free

Converting format with datetimes

With datetimes, you can read a string with one format and output a string with a different format. This means that you can use datetimes to change the format of string dates. The format strings for mapping datetimes are can be found at strftime. Let's say you are asked to process the date of the British Black Wednesday crash into a new format that fits the reporting needs of your company.

This exercise is part of the course

Intermediate Python for Finance

View Course

Exercise instructions

  • Create a format string that fits the original string date, given as org_text.
  • Create a datetime for Black Wednesday and save it as black_wednesday.
  • Create a format string that fits the new format, 'Wednesday, September 16, 1992'.
  • Create a new string date using the new format.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

org_text = "Sep 16 1992"

# Format string for original text
org_format = "%b %____ %____"

# Create datetime for Black Wednesday
black_wednesday = datetime.datetime.____(org_text, org_format)
print(black_wednesday)

# New format: 'Wednesday, September 16, 1992'
new_format = "%____, %____ %d, %Y"

# String in new format
new_text = black_wednesday.____(new_format)
print(new_text)
Edit and Run Code