搜尋

首頁  >  問答  >  主體

python如何轉換時間戳到"2017年6月12日 18點24分"這樣的格式呢?

python如何轉換時間戳到"2017年6月12日 18點24分"這樣的格式呢?謝謝

import time
timestamp = time.time()
time.strftime('%Y年%m月%d日 %H时%M分', time.localtime(timestamp))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence

另外吐槽下,chrome下開啟segmentfault顯示記憶體用完崩潰的錯誤到底什麼時候修啊啊啊啊啊啊!

欧阳克欧阳克2748 天前1155

全部回覆(2)我來回復

  • 漂亮男人

    漂亮男人2017-06-13 09:26:50

    雷雷

    回覆
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-13 09:26:50

    還真被我研究出來種萬能方法,據我百度Google貌似這還是世上獨一份?

    話不多說,下面上解決原理及方案:

    官方文件:https://docs.python.org/3/lib...


    class time.`struct_time`¶

    The type of the time value sequence returned by gmtime(), localtime(), and strptime(). It is an object with a named tupleptime()

    . It is an object with a named tupled 4000m. The following values are present:IndexAttributeValues0(for example, 1993)1range [1, 12]2range [1, 31]3range [0, 23]4range [0, 59]5 description6range [0, 6], Monday is 07range [1, 366]80, 1 or -1; see belowN/Aabbreviation of timezone nameN/Aoffset east of UTC in seconds
    tm_year
    tm_mon
    tm_mday
    tm_hour
    tm_min
    tm_sec range [0, 61]; see (2) in strftime()
    tm_wday
    tm_yday
    tm_isdst
    tm_zone
    tm_gmtoff


    Note that unlike the C structure, the month value is a range of [1, 12], not [0, 11].In calls to mktime(), tm_isdst y is is in effect, and 0 when it is not. A value of -1 indicates that this is not known, and will usually result in the correct state being filled in.
    When a tuple with an incorrect state being filled in.When a tuple with an incorrect state being filled in.When a tuple with an incorrect length is passrrect struct_time, or having elements of the wrong type, a

    TypeError
    is raised.

    看文件可以得知time.localtime()回傳的元組結構,我要用到的是年月日時分,前5個,於是乎,程式碼:

    import time
    print('%s年%s月%s日 %s时%s分' % time.localtime(1497254119.69407)[:5])

    輸出:

    2017年6月12日 15时55分

    搞定。

    🎜轉載請註明出處,謝謝。 🎜

    回覆
    0
  • 取消回覆