Search code examples
pythondatetimeisodate

Extract day of the week and hour from iso datetime stamp in Python


How can I extract the day of the week and the hour of the day from a timestamp in this format?

2020-08-17T01:54:38.000Z

So for the example above I would get Monday and 01 in return.


Solution

  • You could parse the string into a datetime object using strptime with a custom format, and then extract the info you need from it:

    from datetime import datetime
    dateStr = '2020-08-17T01:54:38.000Z'
    dt = datetime.strptime(dateStr,'%Y-%m-%dT%H:%M:%S.%fZ')
    hour = dt.strftime('%H')
    dayOfWeek = dt.strftime('%A')