python教程6.3-time模块datetime模块

 由于time是基于Unix Timestamp,所以其所能表述的日期范围被限定在 1970 – 2038 之间。因此2038年后就不能用time了,建议使用datetime

time模块

有下面几种表示形式:

1、时间戳(timestamp), 表示的是从1970年1⽉1⽇00:00:00开始按秒计算的偏移量。例⼦: 1554864776.161901

2、格式化的时间字符串,⽐如“2020-10-03 17:54”

3、元组(struct_time)共九个元素。由于Python的time模块实现主要调⽤C库,所以各个平台可能 有所不同,mac上:time.struct_time(tm_year=2020, tm_mon=4, tm_mday=10, tm_hour=2, tm_min=53, tm_sec=15, tm_wday=2, tm_yday=100, tm_isdst=0)

 time模块常用方法:

time.localtime([secs]) :将⼀个时间戳转换为当前时区的struct_time。若secs参数未提供, 则以当前时间为准。

time.gmtime([secs]) :将⼀个时间戳转换为struct_time。

time.mktime(t) :将⼀个struct_time转化为时间戳。

time.time() :返回当前时间的时间戳。

time.sleep(secs) :线程推迟指定的时间运⾏,单位为秒。

time.strftime(format[, t]) :把⼀个代表时间的struct_time转化为格式化的时间字符串。如果t未指定,将传⼊ time.localtime()。

time.strptime(string[, format]) :把⼀个格式化时间字符串转化为struct_time。实际上它 和strftime()是逆操作

 datetime模块

几个类

datetime.date:表示⽇期的类。常⽤的属性有year, month, day;

datetime.time:表示时间的类。常⽤的属性有hour, minute, second, microsecond;

datetime.datetime:表示⽇期时间。

datetime.timedelta:表示时间间隔,即两个时间点之间的⻓度。

datetime.tzinfo:与时区有关的相关信息

使用:

d=datetime.datetime.now() 返回当前的datetime⽇期类型, d.timestamp(),d.today(), d.year,d.timetuple()等⽅法可以调⽤

常用方法:

datetime.min、datetime.max:datetime所能表示的最小值与最大值;
datetime.resolution:datetime最小单位;
datetime.today():返回一个表示当前本地时间的datetime对象;
datetime.now([tz]):返回一个表示当前本地时间的datetime对象,如果提供了参数tz,则获取tz参数所指时区的本地时间;
datetime.utcnow():返回一个当前utc时间的datetime对象;

datetime.fromtimestamp(timestamp[, tz]):根据时间戮创建一个datetime对象,参数tz指定时区信息;
datetime.utcfromtimestamp(timestamp):根据时间戮创建一个datetime对象;

datetime.combine(date, time):合并,根据date和time创建一个datetime对象;例如datetime.combine(datetime.datetime.now(),datetime.time.min)
datetime.strptime(date_string, format):将字符串转换为datetime对象;
datetime.strftime(format):将datetime对象转换为字符串;

下面是应用

1、时间加减:

2、时间替换

3、时间和字符串转换

4、strftime格式化去掉日期内的0

 

posted @ 2024-05-08 10:50  JackGIS  阅读(3)  评论(0编辑  收藏  举报