日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python時間戳轉換為字符串與字符串轉換為時間戳_python

作者:追豐少年 ? 更新時間: 2023-05-12 編程語言

實例代碼:

if __name__ == '__main__':
    # 時間戳
    import time
    seconds = time.time()
 
    # 時間戳轉換為字符串
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)))
 
    # 字符串轉換為時間戳
    print(time.mktime(time.strptime("2018-08-07", "%Y-%m-%d")))
    if len(df) > 0:
        # 字符串轉換為時間戳
        x = list(df['日期'])
        x1 = [time.mktime(time.strptime(c, "%Y-%m-%d")) for c in x]
        df['日期時間戳'] = x1
        df.sort_values(by='日期時間戳', inplace=True, ascending=True)
 

綜合范例

這段代碼是字符串先轉為時間格式,時間格式再轉為字符串

pm_str = '6/18/2017 9:52:37 PM'
stTemp = time.strptime(pm_str, "%m/%d/%Y %I:%M:%S %p")
print(stTemp)
str_time = time.strftime("%m-%d-%Y_%H%M%S", stTemp)
print(str_time)

stTemp的輸出結果是

time.struct_time(tm_year=2017, tm_mon=6, tm_mday=18, tm_hour=21, tm_min=52, tm_sec=37, tm_wday=6, tm_yday=169, tm_isdst=-1)

str_time的輸出結果是 06-18-2017_215237

總結

原文鏈接:https://blog.csdn.net/Ghjkku/article/details/122897524

欄目分類
最近更新