Converting unix timestamp string to readable date

前端 未结 15 2561
别跟我提以往
别跟我提以往 2020-11-22 04:30

I have a string representing a unix timestamp (i.e. \"1284101485\") in Python, and I\'d like to convert it to a readable date. When I use time.strftime, I get a

15条回答
  •  感动是毒
    2020-11-22 05:17

    You can convert the current time like this

    t=datetime.fromtimestamp(time.time())
    t.strftime('%Y-%m-%d')
    '2012-03-07'
    

    To convert a date in string to different formats.

    import datetime,time
    
    def createDateObject(str_date,strFormat="%Y-%m-%d"):    
        timeStamp = time.mktime(time.strptime(str_date,strFormat))
        return datetime.datetime.fromtimestamp(timeStamp)
    
    def FormatDate(objectDate,strFormat="%Y-%m-%d"):
        return objectDate.strftime(strFormat)
    
    Usage
    =====
    o=createDateObject('2013-03-03')
    print FormatDate(o,'%d-%m-%Y')
    
    Output 03-03-2013
    

提交回复
热议问题