欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python获取当天日期进行格式转换

程序员文章站 2024-01-06 09:37:10
...
# Python Library
import time


def getToday(format=3):
    """返回今天的日期字串"""
    # format=1      20190305
    # format=2      08:26
    # format=3      2019/03/05
    # format=4      2019/03/05 08:26
    # format=5      190305
    # format=6      2019-03-05
    # format=7      2019/03/05 08:25:40
    # format=8      2019-03-05 08:25
    # format=9      2019-03-05 08:24:51
    # format=10     2019年03月05日 08时50分55秒
    t = time.time()
    date_ary = time.localtime(t)
    print(date_ary)
    if format == 1:
        x = time.strftime("%Y%m%d", date_ary)
    elif format == 2:
        x = time.strftime("%H:%M", date_ary)
    elif format == 3:
        x = time.strftime("%Y/%m/%d", date_ary)
    elif format == 4:
        x = time.strftime("%Y/%m/%d %H:%M", date_ary)
    elif format == 5:
        x = time.strftime("%y%m%d", date_ary)
    elif format == 6:
        x = time.strftime("%Y-%m-%d", date_ary)
    elif format == 7:
        x = time.strftime("%Y/%m/%d %H:%M:%S", date_ary)
    elif format == 8:
        x = time.strftime("%Y-%m-%d %H:%M", date_ary)
    elif format == 9:
        x = time.strftime("%Y-%m-%d %H:%M:%S", date_ary)
    elif format == 10:
        # 将时间元组转换为自定义的字符串格式
        try:
            x = time.strftime("%Y年%m月%d日  %H:%M", date_ary)
        except UnicodeEncodeError as e:
            # 打印错误
            print(e)
        finally:
            x = time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年', m='月', d='日', h='时', f='分', s='秒')
            print(x)
    return x


print(getToday(format=10))

上一篇:

下一篇: