Python parsing date with strptime

后端 未结 2 519
再見小時候
再見小時候 2021-01-20 11:36

I have url that returns date in this format

url_date = \"2015-01-12T08:43:02Z\"

I don\'t know why there are strings, it would have been sim

相关标签:
2条回答
  • 2021-01-20 12:01

    The format you are looking for is - '%Y-%m-%dT%H:%M:%SZ' .

    Example -

    >>> url_date = "2015-01-12T08:43:02Z"
    >>> import datetime
    >>> datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
    datetime.datetime(2015, 1, 12, 8, 43, 2)
    

    For the new requirement in comments -

    if I wanted to get a time back with the strings as in 2015-01-12:08:43:02 which methods should after datetime().datetime()

    You would need to use .strftime() on the datetime.datetime object with the format - '%Y-%m-%d:%H:%M:%S'. Example -

    >>> url_date = "2015-01-12T08:43:02Z"
    >>> dt = datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
    >>> dt.strftime('%Y-%m-%d:%H:%M:%S')
    '2015-01-12:08:43:02'
    

    If you wanted the time component , you can use .time() for that. Example -

    >>> dt = datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
    >>> dt.time()
    datetime.time(8, 43, 2)
    
    0 讨论(0)
  • 2021-01-20 12:11

    You were getting close with the "Z" in your final attempt - you need to specify the T, Z, and colon literal values in your format string.

    >>> import datetime
    >>> url_date = "2015-01-12T08:43:02Z"
    >>> datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
    datetime.datetime(2015, 1, 12, 8, 43, 2)
    
    0 讨论(0)
提交回复
热议问题