【python基础知识学习(5)】Python time strftime() 方法和Python time localtime()方法

(一)Python time strftime() 方法

(1)描述

Python time strftime() 函数用于格式化时间,返回以可读字符串表示的当地时间,格式由参数 format 决定。

(2)语法

strftime()方法语法:

time.strftime(format[, t])

(3)参数

(1)format – 格式字符串。
(2)t – 可选的参数 t 是一个 struct_time 对象。

(4)返回值

返回以可读字符串表示的当地时间。

(5)说明

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 当前时区的名称
%% %号本身

(6)实例

以下实例展示了 strftime() 函数的使用方法:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 通过导入 __future__ 包来兼容 Python3.x print
# 如果使用了 Python3.x 可以删除此行引入
from __future__ import print_function

from datetime import datetime


now = datetime.now() # current date and time

year = now.strftime("%Y")  # %Y 四位数的年份表示(000-9999)
print("year:", year)

month = now.strftime("%m")  # %m 月份(01-12)
print("month:", month)

day = now.strftime("%d")   # %d 月内中的一天(0-31)
print("day:", day)

time = now.strftime("%H:%M:%S") 
'''
     %H 24小时制小时数(0-23)
     %M 分钟数(00=59)
     %S 秒(00-59)
'''
print("time:", time)

date_time = now.strftime("%Y-%m-%d, %H:%M:%S")
print("date and time:",date_time)

运行结果如下:
在这里插入图片描述

(二)Python time localtime()方法

(1)描述

Python time localtime() 函数类似gmtime(),作用是格式化时间戳为本地的时间。 如果sec参数未输入,则以当前时间为转换标准。

(2)语法

localtime()方法语法:

time.localtime([ sec ])

(3)参数

sec – 转换为time.struct_time类型的对象的秒数。

(4)返回值

该函数没有任何返回值。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lingchen1906

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值