How do you convert YYYY-MM-DDTHH:mm:ss.000Z time format to MM/DD/YYYY time format in Python?

前端 未结 5 908
感动是毒
感动是毒 2020-12-08 06:43

For example, I\'m trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What\'s the simplest way of accomplishing this?

相关标签:
5条回答
  • 2020-12-08 07:08

    2008-09-26T01:51:42.000Z is an ISO8601 date and the format can be very diverse. If you want to parse these dates see the python wiki on working with time. It contains some useful links to modules.

    0 讨论(0)
  • 2020-12-08 07:09

    The easiest way is to use dateutil.parser.parse() to parse the date string into a timezone aware datetime object, then use strftime() to get the format you want.

    import dateutil.parser
    
    d = dateutil.parser.parse('2008-09-26T01:51:42.000Z')
    print(d.strftime('%m/%d/%Y'))  #==> '09/26/2008'
    
    0 讨论(0)
  • 2020-12-08 07:31

    I know this is really old question, but you can do it with python datetime.strptime()

    >>> from datetime import datetime
    >>> date_format = "%Y-%m-%dT%H:%M:%S.%fZ" 
    >>> datetime.strptime('2008-09-26T01:51:42.000Z', date_format)
    datetime.datetime(2008, 9, 26, 1, 51, 42)
    
    0 讨论(0)
  • 2020-12-08 07:31
    >>> import time
    >>> timestamp = "2008-09-26T01:51:42.000Z"
    >>> ts = time.strptime(timestamp[:19], "%Y-%m-%dT%H:%M:%S")
    >>> time.strftime("%m/%d/%Y", ts)
    '09/26/2008'
    

    See the documentation of the Python time module for more information.

    0 讨论(0)
  • 2020-12-08 07:32
    def datechange(datestr):
    dateobj=datestr.split('-')
    y=dateobj[0]
    m=dateobj[1]
    d=dateobj[2]
    datestr=d +'-'+ m +'-'+y
    return datestr
    

    U can make a function like this which take date object andd returns you date in desired dateFormat....

    0 讨论(0)
提交回复
热议问题