python datetime.datetime.strptime 模块的简单用法

# -*- coding:utf-8 -*-
import datetime


# 计算两个日期之间相差多少年, 多少天 , 多少月;

# begin_date = input("请输入开始日期:")
# end_date = input("请输入结束日期:")
begin = '2017/01/01'
end = '2018/12/31'
# print(type(begin_date), begin_date)  #  2017/01/01

# 将 字符串开始日期 转成 日期格式   注意 : 格式一定要对应 /
begin_date = datetime.datetime.strptime(begin, '%Y/%m/%d')
print("开始:", begin_date)
end_date = datetime.datetime.strptime(end, '%Y/%m/%d')
print("结束:", end_date)

# 从开始到结束之间有多少个月
month = (end_date.year - begin_date.year)*12 + (end_date.month - begin_date.month)
print(month)
In [26]: from datetime import datetime, date, time

In [27]: dt = datetime(2011, 10, 29, 20, 30, 21)

In [28]: dt.day
Out[28]: 29

In [29]: dt.minute
Out[29]: 30

In [30]: dt.date()
Out[30]: datetime.date(2011, 10, 29)

In [31]: dt.time()
Out[31]: datetime.time(20, 30, 21)

In [32]: dt.strftime("%m/%d/%Y %H:%M")
Out[32]: '10/29/2011 20:30'

In [33]: datetime.strptime("20181006","%Y%m%d")
Out[33]: datetime.datetime(2018, 10, 6, 0, 0)

 

你可能感兴趣的:(python datetime.datetime.strptime 模块的简单用法)