time时间格式输出转换


工作中遇到了很多需要时间转换的时候,记录一下,也不用每次都查看啦

 

1.日期格式化

我用time模块比较多,也可以使用datetime.datetime模块

1)str转date型

time.strptime(date_str, format)

 

2)date型转str

time.strftime(format, date_tuple)

 

3)timestamp转date

datetime.datetime.fromtimestamp(int(timestamp)).strftime(time_format)

 

4)date转timestamp

int(time.mktime(datetime.datetime.strptime(date, time_format).timetuple()))

 

2.日期加减

在datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日期或者时间的差别,也可以用于直接计算日期时间的加减。

1)两个日期相差多少天

day1 = datetime.datetime.strptime('2016-03-29', '%Y-%m-%d')
day2 = datetime.datetime.strptime('2016-03-25', '%Y-%m-%d')
delta = day1 - day2
print delta.days

 

2)某一个时间的第N天

s_t = datetime.datetime.strptime(sometime_str, time_format)
s_t = s_t + datetime.timedelta(days=day_add)

 

3.关于format参数

%a     Abbreviated weekday name
%A     Full weekday name
%b     Abbreviated month name
%B     Full month name
%c     Date and time representation appropriate for locale
%d     Day of month as decimal number (01 - 31)
%H     Hour in 24-hour format (00 - 23)
%I     Hour in 12-hour format (01 - 12)
%j     Day of year as decimal number (001 - 366)
%m     Month as decimal number (01 - 12)
%M     Minute as decimal number (00 - 59)
%p     Current locale's A.M./P.M. indicator for 12-hour clock
%S     Second as decimal number (00 - 59)
%U     Week of year as decimal number, with Sunday as first day of week (00 - 51)
%w     Weekday as decimal number (0 - 6; Sunday is 0)
%W     Week of year as decimal number, with Monday as first day of week (00 - 51)
%x     Date representation for current locale
%X     Time representation for current locale
%y     Year without century, as decimal number (00 - 99)
%Y     Year with century, as decimal number
%z, %Z     Time-zone name or abbreviation; no characters if time zone is unknown
%%     Percent sign


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM