Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Intermediate Python for Finance

Cursus bekijken

Oefeninstructies

  • 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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)
Code bewerken en uitvoeren