Home  >  Article  >  Backend Development  >  Python time operation examples and summary of time formatting parameters

Python time operation examples and summary of time formatting parameters

高洛峰
高洛峰Original
2017-01-12 15:19:171434browse

1. How to get the specific time in the past:

#!/usr/bin/python  
import time  
#取一天前的当前具体时间   
time.strftime('%Y-%m-%d %T',time.localtime(time.time()-24*60*60))  
#取15天前的当前具体时间   
time.strftime('%Y-%m-%d %T',time.localtime(time.time()-15*24*60*60))  
#取15天前当前具体时间的前2小时   
time.strftime('%Y-%m-%d %T',time.localtime(time.time()-15*24*60*60-2*60*60))

2. How to get the specific time in the future:

#!/usr/bin/python   
import time  

#取一天后的当前具体时间   
time.strftime('%Y-%m-%d %T',time.localtime(time.time()+24*60*60))   

#取20天后的当前具体时间   
time.strftime('%Y-%m-%d %T',time.localtime(time.time()+20*24*60*60))   

#取20天后当前具体时间的前2小时   
time.strftime('%Y-%m-%d %T',time.localtime(time.time()+20*24*60*60-2*60*60))

3. Only get the past and future specific values ​​of a certain time unit:

#!/usr/bin/python   
import time  

#取上一月月份   
time.localtime()[1]-1   

#取去年年份   
time.localtime()[0]-1   

#取两个月后的月份   
time.localtime()[1]+2

time.strftime() format command:

%a 星期几的简写   
%A 星期几的全称   
%b 月分的简写   
%B 月份的全称   
%c 标准的日期的时间串   
%C 年份的后两位数字   
%d 十进制表示的每月的第几天   
%D 月/天/年   
%e 在两字符域中,十进制表示的每月的第几天   
%F 年-月-日   
%g 年份的后两位数字,使用基于周的年   
%G 年分,使用基于周的年   
%h 简写的月份名   
%H 24小时制的小时   
%I 12小时制的小时   
%j 十进制表示的每年的第几天   
%m 十进制表示的月份   
%M 十时制表示的分钟数   
%n 新行符   
%p 本地的AM或PM的等价显示   
%r 12小时的时间   
%R 显示小时和分钟:hh:mm   
%S 十进制的秒数   
%t 水平制表符   
%T 显示时分秒:hh:mm:ss   
%u 每周的第几天,星期一为第一天 (值从0到6,星期一为0)   
%U 第年的第几周,把星期日做为第一天(值从0到53)   
%V 每年的第几周,使用基于周的年   
%w 十进制表示的星期几(值从0到6,星期天为0)   
%W 每年的第几周,把星期一做为第一天(值从0到53)   
%x 标准的日期串   
%X 标准的时间串   
%y 不带世纪的十进制年份(值从0到99)   
%Y 带世纪部分的十制年份   
%z,%Z 时区名称,如果不能得到时区名称则返回空字符。   
%% 百分号

For more Python time operation examples and time formatting parameter summary related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn