0

I am trying to convert a string to a datetime format which has the following format

YYYYMMDD:HHMM

As an example:

20200712:1834    which is    2020/07/12 18:34

It is not difficult to extract the information from the string one by one and get year, month, day and the time. But I was wondering if there is a suphisticated way of doing this. For example, I tried the following:

from datetime import datetime
date_time_str = '20200712:1834'
date_time_obj = datetime.strptime(date_time_str, '%y%m%d:%H%M')

Could someone kindly let me know?

afp_2008
  • 1,940
  • 1
  • 19
  • 46
  • 1
    What do you mean by *sophisticated*? If you use `strptime`, change `%y` to `%Y` (full year). If you need a more performant solution, slicing the string and mapping to integer which you feed to datetime is probably faster (but not as clean). – FObersteiner Jul 15 '20 at 05:30
  • btw. you can find a performance comparison of `strptime` vs. explicit slicing [here](https://stackoverflow.com/a/61710371/10197418). – FObersteiner Jul 15 '20 at 07:26

0 Answers0