Skip to content

Instantly share code, notes, and snippets.

@AndyDeNike
Last active September 3, 2019 19:49
Show Gist options
  • Save AndyDeNike/1968a62680f97eb7657766c54e8c8bfd to your computer and use it in GitHub Desktop.
Save AndyDeNike/1968a62680f97eb7657766c54e8c8bfd to your computer and use it in GitHub Desktop.

Date string to datetime object

You've already turned a datetime object into a formatted string with 'strftime' but now, in order to transform a date string into a datetime object, you will need to use 'strptime' !

datetime.strptime() takes two parameters:

First, the string that is written in a datetime format (example 'May 12 2001 2:22PM')

Second, the corresponding format matching the first parameter's date string (formatted using symbols defined to represent datetime; the full list can be found at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) When setting up this second parameter for strptime, make sure the symbols correspond with the part of the date string (example: 'May 22' would be represented by '%b %d', spacing matters!)

Create a function string_to_datetime that takes the test date strings and converts them into datetime objects!

# main.py
def string_to_datetime(string_dt):
pass
# tests.py
def test_string_to_datetime_1():
assert string_to_datetime('Mar 22 2019 4:26PM') == datetime(2019, 3, 22, 16, 26)
def test_string_to_datetime_2():
assert string_to_datetime('Dec 14 1992 8:42PM') == datetime(1992, 12, 14, 20, 42)
# solution.py
from datetime import datetime
def string_to_datetime(string_dt):
return datetime.strptime(string_dt, '%b %d %Y %I:%M%p')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment