Python中time, strftime和strptime

最常用的time.time()返回的是一个浮点数,单位为秒。但strftime处理的类型是time.struct_time,实际上是一个tuple。strptime和localtime都会返回这个类型。

>>> import time
>>> t = time.time()
>>> t
1202872416.4920001
>>> type(t)
<type 'float'>
>>> t = time.localtime()
>>> t
(2008, 2, 13, 10, 56, 44, 2, 44, 0)
>>> type(t)
<type 'time.struct_time'>
>>> time.strftime('%Y-%m-%d', t)
'2008-02-13'
>>> time.strptime('2008-02-14', '%Y-%m-%d')
(2008, 2, 14, 0, 0, 0, 3, 45, -1)

1、strftime的用法

strftime可以用来获得当前时间,可以将时间格式化为字符串等等,还挺方便的。但是需要注意的是获得的时间是服务器的时间,注意时区问题,比如gae撒谎那个的时间就是格林尼治时间的0时区,需要自己转换。

strftime()函数将时间格式化 
我们可以使用strftime()函数将时间格式化为我们想要的格式

#!/usr/bin/python
import time

t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
t = time.mktime(t)
print time.strftime("%b %d %Y %H:%M:%S", time.gmtime(t))

#输出:Feb 17 2009 09:03:38

2.strptime的用法

Python time strptime() 函数根据指定的格式把一个时间字符串解析为时间元组。 
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 当前时区的名称
  • %% %号本身

实例:

#!/usr/bin/python
import time

struct_time = time.strptime("30 Nov 00", "%d %b %y")
print "returned tuple: %s " % struct_time

#输出:returned tuple: (2000, 11, 30, 0, 0, 0, 3, 335, -1)转载:https://blog.csdn.net/Mrzhangjwei/article/details/54377802

猜你喜欢

转载自blog.csdn.net/weixin_40744265/article/details/80879940