Python常用内置模块之Datetime模块

一、相关介绍

1、datetime:用来处理时间和日期的便准库
2、时间戳:从1970年1月1日0时0分0秒,到当前时间的秒数,为浮点数,精确到毫秒。
3、包含模块有:
-date模块 日期对象,常用属性 year,month,day
-time模块 时间对象,hour,minute,second,microsecond
-datetime模块 日期时间对象
-timedelta模块 时间间隔:两个时间之间的长度

二、各个模块的创建

# 创建datetime中的常用对象

from datetime import date,time,datetime,timedelta

#1 创建date 日期对象
d = date(2018,11,17) #必须给年月日,而且是整数
print(d,type(d))

#2 创建time 时间对象
t = time(hour=21,minute=59,microsecond=10000) #参数有时分秒,可以省略,默认为00:00:00
print(t)

#3 创建datetime 日期时间对象
dt = datetime(2018,11,17) # 必须给年月日,而且时整数
print(dt,type(dt))

#4 创建timedelta 时间间隔(时间段)
td = timedelta(days=1.2) #可以用浮点数
print(td,type(td))

#Ctrl+左键点击可查看相应模块的源码

三、datetime对象常用方法(日期时间对象)

1、对象-》字符串
2、字符串-》对象
3、时间戳-》对象
4、对象-》时间戳

from datetime import datetime
now = datetime.now()
print(now)  # 类型是 datetime对象,不是字符串
time_str = now.strftime("%Y-%m-%d %H:%M:%S") # 转换成字符串
print(time_str,type(time_str))

# 时间字符串转换成datetime对象
dt = datetime.strptime("2018/11/17","%Y/%m/%d")
print(dt,type(dt))

# datetime对象转成时间戳(timestamp())
print(now.timestamp())
#date time datetime都是不可变对象

四、时间格式化

%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale’s abbreviated weekday name.#星期的简写
%A Locale’s full weekday name.#星期的全称
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale’s equivalent of either AM or PM.
如当前时间%c:

from datetime import datetime
now = datetime.now()
print(now.strftime("%c"))
#输出
Sat Nov 17 22:21:11 2018

五、时间运算

from datetime import datetime,timedelta
today = datetime.now().date()
tomorrow = today + timedelta(days=1)
yesterday = today -timedelta(days=1)
print(tomorrow,type(today))
print(yesterday,type(yesterday))
#输出
2018-11-18 <class 'datetime.date'>
2018-11-16 <class 'datetime.date'>
#输出
2018-11-18 <class 'datetime.date'>
2018-11-16 <class 'datetime.date'>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值