当前位置:  编程语言>python

Python将日期时间按照格式转换成字符串

 
    发布时间:2013-9-7  


    本文导语:  Python格式化日期时间的函数为datetime.datetime.strftime();由字符串转为日期型的函数为:datetime.datetime.strptime(),两个函数都涉及日期时间的格式化字符串,日期格式化字符串符号英文如下:%a Abbreviated weekday name %A Full weekday nam...

  Python格式化日期时间函数datetime.datetime.strftime();由字符串转为日期型的函数为:datetime.datetime.strptime(),两个函数都涉及日期时间的格式化字符串,日期格式化字符串符号英文如下:

%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

中文翻译如下:  

%a 星期几的简写 Weekday name, abbr.
%A 星期几的全称 Weekday name, full
%b 月分的简写 Month name, abbr.
%B 月份的全称 Month name, full
%c 标准的日期的时间串 Complete date and time representation
%d 十进制表示的每月的第几天 Day of the month
%H 24小时制的小时 Hour (24-hour clock)
%I 12小时制的小时 Hour (12-hour clock)
%j 十进制表示的每年的第几天 Day of the year
%m 十进制表示的月份 Month number
%M 十时制表示的分钟数 Minute number
%S 十进制的秒数 Second number
%U 第年的第几周,把星期日做为第一天(值从0到53)Week number (Sunday first weekday)
%w 十进制表示的星期几(值从0到6,星期天为0)weekday number
%W 每年的第几周,把星期一做为第一天(值从0到53) Week number (Monday first weekday)
%x 标准的日期串 Complete date representation (e.g. 13/01/08)
%X 标准的时间串 Complete time representation (e.g. 17:02:10)
%y 不带世纪的十进制年份(值从0到99)Year number within century
%Y 带世纪部分的十制年份 Year number
%z,%Z 时区名称,如果不能得到时区名称则返回空字符。Name of time zone
%% 百分号

Python3 代码示例

1)获取系统当前时间的字符串

import datetime
def get_formated_time (pstr='%Y-%m-%d %H:%M:%S'):   
    return datetime.datetime.now().strftime(pstr)
if __name__=='__main__':
    print(get_formated_time())

2)时间相减

from datetime import datetime
a = '12:13:50'
b = '12:28:21'
time_a = datetime.strptime(a,'%H:%M:%S')
time_b = datetime.strptime(b,'%H:%M:%S')
print (time_b - time_a).seconds



  • 本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载,整理或搜集自网络.欢迎任何形式的转载,转载请注明出处.
    转载请注明:文章转载自:[169IT-IT技术资讯]
    本文标题:Python将日期时间按照格式转换成字符串
相关文章推荐:


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3