python - 字符串、日期時間轉+格式化

python - 字符串、日期時間轉+格式化

 

#!/usr/bin/env python3
# coding=utf-8
import os
import sys
import argparse
import codecs
import time,datetime

def test():
    # "24/Apr/2020:14:43:38 +0800"
    dt =time.time()
	#格式化輸出
    print(time.strftime('%Y-%m-%d %H:%M:%S [%Z]',time.localtime(dt)))
    print(time.strftime('%y-%m-%d %I:%M:%S [%Z]',time.localtime(dt)))
    print(time.strftime('%d/%b/%Y %H:%M:%S [%Z]',time.localtime(dt)))
    print('-'*30)
	# 字符串轉時間對象
    str = '24/Apr/2020:14:43:38'
    dt = datetime.datetime.strptime(str,'%d/%b/%Y:%H:%M:%S')
    print("%s[%s] => %s[%s]" % (str,type(str),dt,type(dt)))
	#時間對象轉 字符串,格式化輸出
    str = dt.strftime('%Y-%m-%d %H:%M:%S')
    print("%s [%s]" % (str,type(str)))
    pass

test()

'''
python中時間日期格式化符號:
    %y 兩位數的年份表示(00-99)
    %Y 四位數的年份表示(000-9999)
    %m 月份(01-12)
    %d 月內中的一天(0-31)
    %H 24小時制小時數(0-23)
    %I 12小時制小時數(01-12) 
    %M 分鐘數(00=59)
    %S 秒(00-59)    
    %a 本地簡化星期名稱
    %A 本地完整星期名稱
    %b 本地簡化的月份名稱
    %B 本地完整的月份名稱
    %c 本地相應的日期表示和時間表示
    %j 年內的一天(001-366)
    %p 本地A.M.或P.M.的等價符
    %U 一年中的星期數(00-53)星期天爲星期的開始
    %w 星期(0-6),星期天爲星期的開始
    %W 一年中的星期數(00-53)星期一爲星期的開始
    %x 本地相應的日期表示
    %X 本地相應的時間表示
    %Z 當前時區的名稱   
'''

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章