0

I know this has been asked a few times, but my scenario is a little different... The objective I need to accomplish is to convert a string of digits '20150425' (which happens to be a date), into a date format such as, '2015-04-25'. I need this because I am trying to compare date objects in my code, but have one variable type represented as a string.

Example below:
    date = '20150425' ## want to convert this string to date type format
    # conversion here
    conv_date = '2015-04-25' ## format i want it converted into

Hope this is clear. Should not be difficult, just do not know how to do it.

d_rooney
  • 89
  • 2
  • 15

2 Answers2

1

This works

from datetime import datetime
date = '20150425'
date_object = datetime.strptime(date, '%Y%m%d')

date_object
>>> datetime.datetime(2015,4,25,0,0)
user308827
  • 21,227
  • 87
  • 254
  • 417
0

Assuming the date strings will always be 8 characters:

date = '20150425'
fdate = "{}-{}-{}".format(date[0:4], date[4:6], date[6:]) # 2015-04-25

Alternatively, you can go the "heavier" route and use the actual datetime class:

from datetime import datetime
date = '20150425'
dt = datetime.strptime(date, "%Y%m%d")
dt.strftime("%Y-%m-%d") # 2015-04-25
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159