首页 > 编程 > Python > 正文

Python之时间和日期使用小结

2020-02-16 01:07:59
字体:
来源:转载
供稿:网友

对于日期的操作可以说是比较常见的case了,日期与格式化字符串互转,日期与时间戳互转,日期的加减操作等,下面主要介绍下常见的需求场景如何实现

1. 基本包引入

主要需要引入时间和日期的处理包,后面的基本操作都是基于此

import datetimeimport time

2. 获取当前时间

获取当前时间,有几种方式,分别使用time和datetime来演示

a. time

获取当前时间,格式化为字符串输出

now = time.strftime("%Y-%m-%d %H:%M:%S")print(now)

获取当前时间,以时间戳方式输出,结果为float类型,单位为s

now=time.time()print(now)

b. datetime

直接调用now()函数获取当前时间,返回datetime类型对象

now = datetime.datetime.now()print(now)

3. 时间戳转datetime

函数: datetime.datetime.fromtimestamp()

将时间戳转换为datetime类型,因为后者可以进行日期的计算(如常见的加减或者格式化)

# 获取当前的时间戳now = time.time()# 将时间差转换为datetime对象date = datetime.datetime.fromtimestamp(now)print(date)

4. 时间戳转格式化日期a. time

函数 time.strftime(format, localtime) 和 time.localtime(timestamp)

借助time的time.strftime函数来实现转换,这里还需要做一个额外的处理,将时间戳转换为struct_time 对象

now = time.time()# 首先格式化时间戳为struct_time对象,接着格式化输出time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))

b. datetime

函数 datetime.datetime.fromtimestamp 与 datetime.datetime.strftime()

借助前面的知识点即可实现,先将timestamp转换为datetime, 然后将datetime格式化为字符串

now=time.time()date =datetime.datetime.fromtimestamp(now)date.strftime('%Y-%m-%d %H:%M:%S')

5. 字符串转时间戳

函数 strptime(str) 与 time.mktime(struct_time)

前面格式化输出字符串时,主要利用的是strftime,这里则主要使用 strptime

now='2019-02-11 18:45:22'struct_time=time.strptime(now , '%Y-%m-%d %H:%M:%S')timestamp=time.mktime(struct_time)            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表