标准库time,datetime,random,calendar的使用

Python时间处理的标准函数库datetime提供了一批显示日期和时间的格式化方法。

前提介绍:datetime库的建立是基于格林威治时间之上,即能够输出从格林威治时间1970年1月1日00:00:00开始至当下的时间,且每天有3600*24秒的精确定义,因此当我们的程序中有涉及到时间的参数,我们可以调用datetime库中的一系列有关时间的参数调用,来大大简化我们的编程。

datetime库的常用日期和时间的表达方式:
datetime.date:日期表示类,可以表示年,月,日。
datetime.time:时间表示类,输出小时、分钟、秒、毫秒
datetime.now:获得当前的时间和日期
datetime.utcnow()获得当前时间对应的UTC(世界标准时间)
strftime()时间格式化,可以用来输出任何通用的时间格式datetime.date.isocalendar():返回格式如(year,month,day)的元组
datetime.date.isoformat():返回格式如YYYY-MM-DD
datetime.date.isoweekday():返回给定日期的星期(0-6)
datetime.date.replace(year,month,day):替换给定日期,但不改变原日期
datetime.date.strftime(format):把日期时间按照给定的format进行格式化。
datetime.date.timetuple():返回日期对应的time.struct_time对象

下面是个代码极其运行:

 1. datetime.now

from datetime import datetime
today=datetime.now()
print(today)
2019-04-07 20:35:31.815312



2.datetime.utcnow

from datetime import datetime
today=datetime.utcnow()
print(today)
2019-04-07 12:47:46.039084

random函数的使用

Python标准库中的random函数,可以生成随机浮点数、整数、字符串,甚至帮助你随机选择列表序列中的一个元素,打乱一组数据等。
常用的random函数有如下几种:
注意:random的输入一定要用列表形式。
1.random() 返回0<=n<1之间的随机实数n;

2.choice(seq) 从序列seq中返回随机的元素;

import random
a=random.choice([1,2,3])
print(a)

3.getrandbits(n) 以长整型形式返回n个随机位;

4.shuffle(seq[, random]) 原地指定seq序列;

5.sample(seq, n) 从序列seq中选择n个随机且独立的元素;

import random
a=random.choice(['A', 'B', 'C', 'D', 'E'])
print(a)

6.random.sample()可以从指定的序列中,随机的截取指定长度的片断,不作原地修改。

calendar函数的应用

calendar函数是Python的内置函数,包含一系列有关日历的函数,在我们平常的函数编写中可以运用到。
1.calendar import calendar
返回指定年的某月
def get_month(year, month):
return calendar.month(year, month)

返回指定年的日历
def get_calendar(year):
return calendar.calendar(year)

判断某一年是否为闰年,如果是,返回True,如果不是,则返回False
def is_leap(year):
return calendar.isleap(year)

返回某个月的weekday的第一天和这个月的所有天数
def get_month_range(year, month):
return calendar.monthrange(year, month)

返回某个月以每一周为元素的序列
def get_month_calendar(year, month):
return calendar.monthcalendar(year, month)

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值