Converting a string to a formatted date-time string using Python

前端 未结 5 1255
予麋鹿
予麋鹿 2020-12-05 07:37

I\'m trying to convert a string \"20091229050936\" into \"05:09 29 December 2009 (UTC)\"

>>>import time
>>>s = time.strptime(\"200912290509         


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

    You can use easy_date to make it easy:

    import date_converter
    my_datetime = date_converter.string_to_string("20091229050936", "%Y%m%d%H%M%S", "%H:%M %d %B %Y (UTC)")
    
    0 讨论(0)
  • 2020-12-05 08:04

    For me this is the best and it works on Google App Engine as well

    Example showing UTC-4

    import datetime   
    UTC_OFFSET = 4
    local_datetime = datetime.datetime.now()
    print (local_datetime - datetime.timedelta(hours=UTC_OFFSET)).strftime("%Y-%m-%d %H:%M:%S")
    
    0 讨论(0)
  • 2020-12-05 08:07

    time.strptime returns a time_struct; time.strftime accepts a time_struct as an optional parameter:

    >>>s = time.strptime(page.editTime(), "%Y%m%d%H%M%S")
    >>>print time.strftime('%H:%M %d %B %Y (UTC)', s)
    

    gives 05:09 29 December 2009 (UTC)

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

    For datetime objects, strptime is a static method of the datetime class, not a free function in the datetime module:

    >>> import datetime
    >>> s = datetime.datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
    >>> print s.strftime('%H:%M %d %B %Y (UTC)')
    05:09 29 December 2009 (UTC)
    
    0 讨论(0)
  • 2020-12-05 08:11
    from datetime import datetime
    s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
    print("{:%H:%M %d %B %Y (UTC)}".format(s))
    
    0 讨论(0)
提交回复
热议问题