python学习笔记2
python中的时间和日期
· python中提供了time、datetime和calendar模块可以用于格式化时间和日期。python中时间日期的格式花符号如下:
%y 两位数的年份表示(00~99)
%Y 四位数的年份表示(0000~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 当前时区的名称
%% %号本身
time模块包含了以下内置函数,既有时间处理的函数,也有转换时间格式的函数
FUNCTIONS
asctime(...)
asctime([tuple]) -> string
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
When the time tuple is not present, current time as returned by localtime()
is used.
ctime(...)
ctime(seconds) -> string
Convert a time in seconds since the Epoch to a string in local time.
This is equivalent to asctime(localtime(seconds)). When the time tuple is
not present, current time as returned by localtime() is used.
get_clock_info(...)
get_clock_info(name: str) -> dict
Get information of the specified clock.
gmtime(...)
gmtime([seconds]) -> (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 UTC (a.k.a.
GMT). When 'seconds' is not passed in, convert the current time instead.
If the platform supports the tm_gmtoff and tm_zone, they are available as
attributes only.
localtime(...)
localtime([seconds]) -> (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.
When 'seconds' is not passed in, convert the current time instead.
mktime(...)
mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch.
Note that mktime(gmtime(0)) will not generally return zero for most
time zones; instead the returned value will either be equal to that
of the timezone or altzone attributes on the time module.
monotonic(...)
monotonic() -> float
Monotonic clock, cannot go backward.
monotonic_ns(...)
monotonic_ns() -> int
Monotonic clock, cannot go backward, as nanoseconds.
perf_counter(...)
perf_counter() -> float
Performance counter for benchmarking.
perf_counter_ns(...)
perf_counter_ns() -> int
Performance counter for benchmarking as nanoseconds.
process_time(...)
process_time() -> float
Process time for profiling: sum of the kernel and user-space CPU time.
process_time_ns(...)
process_time() -> int
Process time for profiling as nanoseconds:
sum of the kernel and user-space CPU time.
sleep(...)
sleep(seconds)
Delay execution for a given number of seconds. The argument may be
a floating point number for subsecond precision.
strftime(...)
strftime(format[, tuple]) -> string
Convert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
strptime(...)
strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
thread_time(...)
thread_time() -> float
Thread time for profiling: sum of the kernel and user-space CPU time.
thread_time_ns(...)
thread_time() -> int
Thread time for profiling as nanoseconds:
sum of the kernel and user-space CPU time.
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.
time_ns(...)
time_ns() -> int
Return the current time in nanoseconds since the Epoch.
其中time模块内还包含了以下两个非常重要的属性
time.timezone 属性timezone是当地时区(未启动夏令时)距离格林尼治的便宜秒数(>0,美洲;<=0大部分欧洲,亚洲,非洲)
time.tzname 属性tzname包含一对根据情况的不同而不同的字符串,分别是带和不带夏令时本地时区名称
日历(calendar)模块的函数都是日历相关的,例如打印某月的字符日历。星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar。setfirstweekday()函数。模块包含了以下内置函数
calendar = formatyear(theyear, w=2, l=1, c=6, m=3) method of TextCalendar instance
Returns a year's calendar as a multi-line string.
firstweekday = getfirstweekday() method of TextCalendar instance
isleap(year)
Return True for leap years, False for non-leap years.
leapdays(y1, y2)
Return number of leap years in range [y1, y2).
Assume y1 <= y2.
month = formatmonth(theyear, themonth, w=0, l=0) method of TextCalendar instance
Return a month's calendar string (multi-line).
monthcalendar = monthdayscalendar(year, month) method of TextCalendar instance
Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero.
monthrange(year, month)
Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
year, month.
prcal = pryear(theyear, w=0, l=0, c=6, m=3) method of TextCalendar instance
Print a year's calendar.
prmonth(theyear, themonth, w=0, l=0) method of TextCalendar instance
Print a month's calendar.
setfirstweekday(firstweekday)
timegm(tuple)
Unrelated but handy function to calculate Unix timestamp from GMT.
weekday(year, month, day)
Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31).
weekheader = formatweekheader(width) method of TextCalendar instance
Return a header for a week.
time实例
import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为:",localtime)
print(time.strftime("%a %b %d %H:%M:%S %Y",time.localtime()))
print(time.ctime())
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y-%m-%d %X'))
datetime模块实例
import datetime
print(datetime.datetime.now()) #获取当前时间
from datetime import datetime,timedelta
dt_now = datetime.now()
print(dt_now)
print(dt_now.date())
print(dt_now.time())
print(dt_now.timestamp())
print(dt_now.strftime("%Y %m %d"))
d1 = datetime.strptime("2021-03-31 13:09:17","%Y-%m-%d %H:%M:%S")
print(d1)
d2 = d1 + timedelta(seconds=1)
print(d2)
如何获取当前时间并格式化输出
可以使用time或datetime模块
import time
print(time.strftime("%Y-%m-%d %X"))
import datetime
print(datetime.datetime.now().strftime('%Y-%m-%d %X'))
打印前一天的本地时间,参考格式为“2019-05-25 10:20:34”
import datetime
yesterday_datetime = datetime.datetime.now()-datetime.timedelta(days=1)
yesterday_str = datetime.datetime.strftime(yesterday_datetime,"%Y-%m-%d %H:%M:%S")
print(yesterday_str)
用函数打印昨天的日期
import datetime
def getYesterday():
today = datetime.date.today()
onday = datetime.timedelta(days=1)
yesterday = today - onday
return yesterday
print(getYesterday())
计算每个月的天数
import calendar
monthRange = calendar.monthrange(2021,3)
print(monthRange)
print(calendar.mdays)
print(calendar.mdays[9])
获取某个月的日历
import calendar
cal = calendar.month(2021,3)
print(cal)