python笔记:time,datetime,calendar
程序员文章站
2022-07-14 23:20:53
...
time
import time
# striptime函数 和 mktime函数
def str_time_to_str(str_time):
# striptime()返回的是time.struct_time(tm_year=2019, tm_mon=12, tm_mday=12, tm_hour=12, tm_min=12, tm_sec=12, tm_wday=3, tm_yday=346, tm_isdst=-1)
# striptime()参数必须是字符串时间+时间格式化,不能省略
my_struct_time = time.strptime(str_time,'%Y-%m-%d %H:%M:%S')
#利用mktime将struct_time转换成时间戳
# mktime()接收struct_time对象作为参数,返回用秒数来表示时间的浮点数。也可以接收完整的9位元组元素。
# t = (2016, 2, 17, 17, 3, 38, 1, 48, 0)
# secs = time.mktime( t )
my_time_stamp = time.mktime(my_struct_time)
print(my_time_stamp)
#strftime函数,将时间展示格式从一种转换为另一种,例如从2019/11/11 转换成2019-11-11
def change_time_format_by_strftime(str_time):
# 套路都是先转换为struct_time
my_struct_time = time.strptime(str_time,'%Y/%m/%d %H:%M:%S')
my_new_format_time = time.strftime('%Y-%m-%d %H:%M:%S',my_struct_time)
print(my_new_format_time)
if __name__=="__main__":
# strptime()是核心,因为它的返回结果是struct_time
str_time_to_str('2019-12-12 12:12:12')
change_time_format_by_strftime('2019/12/12 12:12:12')
datetime
import datetime
import time
def get_yesterday():
# 获取今天的日期
today = datetime.date.today()
print(today)
# 获取一天的时间间隔,输出为 1 day,0:00:00
oneday = datetime.timedelta(days=1)
print(oneday)
# 今天减去一天,就是昨天
yesterday = today-oneday
return yesterday
def get_days_ago(n):
# 得到的格式是---标准格式,同时秒后面带小数点
ndaysago = datetime.datetime.now()-datetime.timedelta(days=n)
print(ndaysago)
# 时间转换为时间戳
timestamp = int(time.mktime(ndaysago.timetuple()))
print(timestamp)
# 转换格式,为秒后面为小数点
change_into_other_style = ndaysago.strftime("%Y/%m/%d %H:%M:%S")
print(change_into_other_style)
def stamp_into_time(time_stamp,n):
# 将时间转换成标准时间格式用utcfromtimestamp
date_arr = datetime.datetime.utcfromtimestamp(time_stamp)
ndaysago = date_arr - datetime.timedelta(days=n)
print(ndaysago)
def time_stampintotime(my_stamp):
# 拿到的是时间戳
now = time.time()
print(now)
print(my_stamp)
# 拿到得失time.struct_time格式:
# time.struct_time(tm_year=2020, tm_mon=1, tm_mday=6, tm_hour=17, tm_min=42, tm_sec=38, tm_wday=0, tm_yday=6, tm_isdst=0)
time_arr = time.localtime(now)
time_arr2 = time.localtime(my_stamp)
print(time_arr)
print(time_arr2)
# 从struct_time转换为其他格式的时间,用strftime
otherstyletime = time.strftime("%Y-%m-%d %H:%M:%S",time_arr)
otherstyletime2 = time.strftime("%Y-%m-%d %H:%M:%S", time_arr2)
print(otherstyletime)
print(otherstyletime2)
def datetime_stampintotime(my_stamp):
#拿到的是正常的时间格式,但是秒后面有小数点
now = datetime.datetime.now()
print(now)
print(my_stamp)
# datetime中针对时间戳还需要将时间戳处理一下,已经是标准时间格式了
datetime_arr = datetime.datetime.utcfromtimestamp(my_stamp)
print(datetime_arr)
# 通过XX.strftime()函数将XX转换为标准时间格式
otherstyletime = now.strftime("%Y-%m-%d %H:%M:%S")
otherstyletime2 = datetime_arr.strftime("%Y-%m-%d %H:%M:%S")
print(otherstyletime)
print(otherstyletime2)
# print(get_yesterday())
# get_days_ago(3)
# stamp_into_time(157283888884,3)
# time_stampintotime(1557502800)
datetime_stampintotime(1557502800)
calendar
# 日历相关
import calendar
def display_month(yyyy,mm):
if mm<1 or mm>12:
return u'输入的月份不存在'
else:
print('{}-{}的月历展示:'.format(yyyy,mm))
print(calendar.month(yyyy,mm))
def display_monthrange(yyyy,mm):
if mm<1 or mm>12:
return u'输入的月份不存在'
else:
# 结果是一个元组,第一个代表是星期几,0-6,0代表周一;第二个是本月有多少天
print('{}-{}:'.format(yyyy,mm))
print(calendar.monthrange(yyyy,mm))
def display_calendar_year(yyyy):
if mm < 1 or mm > 12:
return u'输入的月份不存在'
else:
# 打印2019年,3个月一行,横向看每天相差w个字符,每月相差c个字符,l为每星期占用的行数,每行长度为 21*W+18+2*C
# print('{}-{}:'.format(yyyy, mm))
# 打印年历,3个月一行,横向看每天相差w个字符,每月之间相差c个字符,l是每星期占用的行数,每行的总长度:21w+18+2c
print(calendar.calendar(yyyy,w=2,l=1,c=6))
def display_calendar_month(yyyy,mm):
if mm < 1 or mm > 12:
return u'输入的月份不存在'
else:
# 如果是打印某个月的,则用month,同时有个月份参数,没有c参数,而且方法名是month
# print('{}-{}:'.format(yyyy, mm))
# 打印年历,3个月一行,横向看每天相差w个字符,每月之间相差c个字符,l是每星期占用的行数,每行的总长度:21w+18+2c
print(calendar.month(yyyy,mm,w=2,l=2))
if __name__ == "__main__":
yyyy = int(input('请输入年份,如1950:'))
mm = int(input('请输入月份,如04:'))
display_month(yyyy,mm)
display_monthrange(yyyy,mm)
display_calendar_year(yyyy)
display_calendar_month(yyyy,mm)
综上:三者的综合表现(部分为引用内容,仅供参考)
import calendar
import time
import datetime
# time模块中的三种时间形式
print("time stamp:", time.time()) # 时间戳
print("local time:", time.localtime()) # struct_time类型的本地时间:(a,b,c,d)这种形式的
print("utc time:", time.gmtime()) # struct_time类型的utc时间:(a,b,c,d)这种形式的
# time模块中,三种时间形式之间的转换
time_stamp = time.time() # 时间戳
local_time = time.localtime(time_stamp) # 时间戳转struct_time类型的本地时间
utc_time = time.gmtime(time_stamp) # 时间戳转struct_time类型的utc时间
time_stamp_1 = time.mktime(local_time) # struct_time类型的本地时间转时间戳
time_stamp_2 = calendar.timegm(utc_time) # struct_time类型的utc时间转时间戳
print(time_stamp, time_stamp_1, time_stamp_2)
# time模块中,三种时间形式和字符串之间的转换
print(time.ctime(time_stamp)) # 时间戳转字符串(本地时间字符串),返回格式如Tue Feb 17 10:00:18 2013
print(time.asctime(local_time)) # struct_time类型的本地时间转字符串,接受时间元组并返回一个可读的形式为"Tue Dec 11 18:07:14 2008"
print(time.asctime(utc_time)) # struct_time类型的utc时间转字符串,接受时间元组并返回一个可读的形式为"Tue Dec 11 18:07:14 2008"
print(time.strftime("%Y-%m-%d, %H:%M:%S, %w", local_time)) # struct_time类型的本地时间转字符串:自定义格式
print(time.strftime("%Y-%m-%d, %H:%M:%S, %w", utc_time)) # struct_time类型的utc时间转字符串:自定义格式
struct_time = time.strptime("2016-11-15, 15:32:12, 2", "%Y-%m-%d, %H:%M:%S, %w") # 字符串转struct_time类型
# datetime模块中datetime类的用法
my_datetime_local = datetime.datetime.now() # 获取datetime.datetime类型的本地时间,正常的时间格式,非时间戳
my_datetime_utc = datetime.datetime.utcnow() # 获取datetime.datetime类型的utc时间
print(my_datetime_local.strftime("%Y-%m-%d, %H:%M:%S, %w")) # datetime.datetime类型转字符串
print(my_datetime_utc.strftime("%Y-%m-%d, %H:%M:%S, %w")) # datetime.datetime类型转字符串
a_datetime = datetime.datetime.strptime("2016-11-15, 15:32:12, 2", "%Y-%m-%d, %H:%M:%S, %w") # 字符串转datetime.datetime格式
# datetime.datetime类和时间戳、struct_time类型之间的转换
time_stamp = my_datetime_local.timestamp() # datetime类型转时间戳
print(time_stamp)
my_datetime_local = datetime.datetime.fromtimestamp(time.time()) # 时间戳转datetime.datetime类型的本地时间
my_datetime_utc = datetime.datetime.utcfromtimestamp(time.time()) # 时间戳转datetime.datetime类型的utc时间
print(my_datetime_local, my_datetime_utc)
print(my_datetime_local.timetuple()) # datetime类型转struct_time类型
print(my_datetime_utc.utctimetuple()) # datetime类型转struct_time类型
#给个年月日计算是一年中的第几天,和是星期几
import datetime
from functools import reduce
def counter_days(yyyy,mm,dd):
leap_moths = [0,31,29,31,30,31,30,31,31,30,31,30]
not_leap_months = [0,31,28,31,30,31,30,31,31,30,31,30]
def is_leap_year(yyyy):
if yyyy%400==0 or (yyyy%100 !=0 and yyyy%4==0):
return True
# python仲有datetime.weekday()方法,直接可以输出是星期几
week_day = datetime.datetime(yyyy, mm, dd).weekday() + 1
if is_leap_year(yyyy):
days = reduce(lambda x,y:x+y,leap_moths[:mm])+int(dd)
else:
days = reduce(lambda x, y: x + y, not_leap_months[:mm]) + int(dd)
return days,week_day
# datetime对象的strftime()方法,计算星期几,返回值为1-7
def check_weekday(yyyy,mm,dd):
anyday = int(datetime.datetime(yyyy,mm,dd).strftime("%w"))
print("星期%d" % (anyday))
if __name__=="__main__":
print(counter_days(2020,4,14))
check_weekday(2020,4,14)
推荐阅读
-
Python中time模块与datetime模块在使用中的不同之处
-
Python Datetime模块和Calendar模块用法实例分析
-
Python3.5内置模块之time与datetime模块用法实例分析
-
python_time和datetime模块
-
Python3 标准库:calendar,time
-
python学习笔记:第21天 常用内置模块之collections和time
-
模块使用:time、datetime、calendar、sys、os、os.path、normcase和normapath、random、json、pickle
-
Python中的time模块和calendar模块
-
Python时间模块datetime、time、calendar的使用方法
-
Python中的time、datetime、calendar模块(时间模块)