Python-日期时间模块
Python和时间相关的模块有2个:time、datetimetime模块,常用的方法
1)time()方法:返回UTC时间1970年1月1日至今有多少秒
time(...)
time() -> floating point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
2)localtime()方法:返回当地时区时间,参考gmtime
localtime(...)
localtime() -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)
Convert seconds since the Epoch to a time tuple expressing local time.
time.localtime(time.time())
time.struct_time(tm_year=2013, tm_mon=1, tm_mday=13, tm_hour=17, tm_min=52, tm_sec=26, tm_wday=6, tm
_yday=13, tm_isdst=0)
3)strftime():按指定format格式化时间成字符串
strftime(...)
strftime(format[, tuple]) -> string
Convert a time tuple to a string according to a format specification.
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
'2013-01-13 17:58:39'
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 当前时区的名称
%% %号本身
4)sleep():线程休眠多少秒
sleep(...)
sleep(seconds)
Delay execution for a given number of seconds.The argument may be
a floating point number for subsecond precision.
datetime模块,使用它可以获取毫秒时间,感觉要比time强大
1)today()和now():获取当前时间
d = datetime.datetime
d.now()
datetime.datetime(2013, 1, 13, 18, 39, 19, 903000)
d.now().microsecond
93000
2)strftime()格式化时间
d.now().strftime('%Y-%m-%d %H:%M:%S')
'2013-01-13 18:42:14'
除此之外,还有calendar模块和日期时间有关
calendar模块:This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. Parameters that specify dates are given as integers. For related functionality, see also the datetime and time modules.
c = calendar.TextCalendar()
c.setfirstweekday(6)
c.prmonth(2013,1)
-----------------------
January 2013
Su Mo Tu We Th Fr Sa
12345
6789 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
页:
[1]