Python datetime包函数简单介绍

yipeiwu_com5年前Python基础

一、datetime包(上接连载7内容)

1.函数:datetime

(1)用法:输入一个日期,来返回一个datetime类​

(2)格式:datetime.datetime(年,月,日,hour=,minute=,second=)

其中hour,minute,second可选

(3)附加类方法:

today():返回本地当前时间

now():返回本地当前时间

utcnow():返回本地当前时间

fromtimestamp(时间戳):返回时间戳的本地时间

dt = datetime.datetime(2019,6,10)
print(type(dt)) 
print(dt.today()) 
print(dt.now()) 
print(dt.utcnow()) 
print(dt.fromtimestamp(time.time()))
print(dt)

2.函数:timedelta

(1)用法:表示一个时间间隔

(2)格式:datetime.timedelta(days=?,hours=?,minutes=?,seconds=?)

试了一下,month和years并不支持

t1 = datetime.datetime.now()
print(t1.strftime("%Y{a}%m{a}%d{b}%H{c}%M{c}%S".format(a="/",b=" ",c=":"))) 
t2 =datetime.timedelta(hours=1,days=2,minutes=1,seconds=2) 
print((t1+t2).strftime("%Y{a}%m{a}%d{b}%H{c}%M{c}%S".format(a="/",b=" ",c=":")))

二、timeit包

1.函数:timeit

(1)用法:时间测量工具,测量程序运行时间间隔的实验

(2)格式:timeit.timeit(stmt=代码块/函数名,number=执行次数,)

c=''' 
sum= [] 
for i in range(1000): 
  sum.append(i) 
''' 
#利用timeit调用代码,执行100000次,查看运行时间
t4 = timeit.timeit(stmt = "[i for i in range(1000)]",number=100000) 
#测试代码c执行100000次的运行结果 
t5 = timeit.timeit(stmt=c,number=100000) 
print(t4) 
print(t5)

三、源码

d17_5_datetime_package

地址:https://github.com/ruigege66/Python_learning/blob/master/d17_5_datetime_package

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决pycharm工程启动卡住没反应的问题

今天早上用pycharm启动django工程的时候,一直卡在如下提示: Performing system checks... System check identified no...

如何用python写一个简单的词法分析器

如何用python写一个简单的词法分析器

编译原理老师要求写一个java的词法分析器,想了想决定用python写一个。 目标 能识别出变量,数字,运算符,界符和关键字,用excel表打印出来。 有了目标,想想要怎么实现词法分析器...

pandas基于时间序列的固定时间间隔求均值的方法

pandas基于时间序列的固定时间间隔求均值的方法

如果index是时间序列就不用转datetime;但是如果时间序列是表中的某一列,可以把这一列设为index 例如: 代码: DF=df2.set_index(df1['time_...

python getopt详解及简单实例

 python getopt详解 函数原型: getopt.getopt(args, shortopts, longopts=[]) 参数解释: args:args...

详解Python 模拟实现生产者消费者模式的实例

详解Python 模拟实现生产者消费者模式的实例 散仙使用python3.4模拟实现的一个生产者与消费者的例子,用到的知识有线程,队列,循环等,源码如下: Python代码 impo...