日期strftime、strptime

#time strftime(format,tuple)接收时间元组,返回表示时间的字符串。str-format-time, 时间字符串格式化,即我们看到的格式。
#time strptime(string,format)把时间字符串,解析成一个时间元组。 str-parse-time,时间字符串语法化,即计算机理解的格式。
 
示例:
import time 
 
t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print(t)
print(type(t))
 
q = time.strptime(t,'%Y-%m-%d %H:%M:%S')#format和t的格式要一致,都有时分秒或者都没有
print q
print(type(q))
 
程序输出:
2018-06-27 13:33:13
type 'str'
time.struct_time(tm_year=2018, tm_mon=6, tm_mday=27, tm_hour=13, tm_min=33, tm_sec=13, tm_wday=3, tm_yday=178, tm_isdst=-1)
type 'time.struct_time'
 
 
 
 
 
示例:自定义输入日期,返回日期相关的信息。
import time
a = raw_input('请输入日期,格式为yyyy-mm-dd')
t = time.strptime(a, '%Y-%m-%d')
 
print t    #生成struct_time,元组元素结构
print t.tm_yday   #获取tm_yday元素,即一年中的第几天
 
print time.gmtime()    #和上述逻辑一样,只是获取的是当前系统时间,不是自行输入的时间
print time.gmtime().tm_yday
 
键盘输入:
2018-02-12
程序输出:
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=12, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=43, tm_isdst=-1)
43
time.struct_time(tm_year=2018, tm_mon=6, tm_mday=27, tm_hour=3, tm_min=48, tm_sec=15, tm_wday=3, tm_yday=178, tm_isdst=0)
178
 
 

猜你喜欢

转载自www.cnblogs.com/myshuzhimei/p/11751320.html