datetime模块简介

在 Python 中,与时间处理有关的模块包括:time,datetime 以及 calendar
在此仅对datetime模块的使用:

1、认识datetime

    datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

    The year, month and day arguments are required. tzinfo may be None, or an
    instance of a tzinfo subclass. The remaining arguments may be ints.

2、使用datetime,首先得导入datetime模块

import datetime
print(datetime.now())   # AttributeError: module 'datetime' has no attribute 'now'

要像这样的话,显示当前时间就会报错,原因是datetime模块下没有now()这个方法。这个错误我犯过,所以在文章开头就先提醒一下读者,这个模块内的类内方法应该如何调用。正确方法如下:

# 仅用import时
import datetime
print(datetime.datetime.now())   # 2019-08-08 09:51:33.248204
#使用from导入datetime中的类内方法
from datetime import datetime
# 获取当前时间
print(datetime.now())
# 获取世界时间
print(datetime.utcnow())

3、两日期之间求日期差(strptime转换)

首先你得有两个日期:

import datetime

def get_day():
    x = input("请输入检查的日期(YYYY-MM-DD)\n")
    x = datetime.datetime.strptime(x , "%Y-%m-%d")
    print("输入日期和今天间隔{}天".format((x - datetime.datetime.now()).days + 1))


if __name__ == '__main__':
    get_day()

4、strftime用法:将原来的datetime.datetime这个数据类型转换成str数据类型,方便python 操作,用户理解。

import datetime

date = datetime.datetime.now()
print(date,type(date))  # 2019-08-08 12:08:34.704204 <class 'datetime.datetime'>
datestr = date.strftime("%Y-%m-%d")
print(datestr,type(datestr))    # 2019-08-08 <class 'str'>
datestr2 = str(date)
print(datestr2,type(datestr2))  # 2019-08-08 12:08:34.704204 <class 'str'>

strftime将时间类型转换成str,strptime将str转换成时间类型。

5、分开获取年月日+时分秒

import datetime


# 仅获取当前的年月日
y = datetime.datetime.now().year
m = datetime.datetime.now().month
d = datetime.datetime.now().day
print("{}年{}月{}日".format(y ,m ,d))      #2019年8月8日


# 仅获取当前的时分秒
h = datetime.datetime.now().hour
m = datetime.datetime.now().minute
s = datetime.datetime.now().second
# print(type(h))    int
print('{}:{}:{}'.format(h,m,s))   # 12:57:49

最后带一下calender模块

import calendar

c = calendar.month(2019, 8)
print("以下为2019年8月的日历:")
print(c)

"""
以下为2019年8月的日历:
    August 2019
Mo Tu We Th Fr Sa Su
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
"""

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值