Search code examples
pythondatetimestrptime

turn string into time


How would I get this string '201806070908' into a datetime object? Right now this is YYYYMMDDMMSS. I could get rid of Seconds (S) if needed. I was looking at strptime() but I'm not sure this could be used. It is possible to convert this? The time is part of a directory name and I am looking to upload the most recent file back to another machine.

If anyone can assist or point me in the right direction, then that would be great. Thanks


Solution

  • strptime should work:

    import datetime
    
    s = '201806070908'
    
    dt = datetime.datetime.strptime(s, '%Y%m%d%M%S')
    
    datetime.datetime(2018, 6, 7, 0, 9, 8)
    

    You can test that this worked:

    >>> dt.day
    7
    >>> dt.month
    6
    >>> dt.year
    2018
    >>> dt.minute
    9
    >>> dt.second
    8