主页 > 知识库 > Python datetime模块的使用示例

Python datetime模块的使用示例

热门标签:呼叫中心市场需求 企业做大做强 电话运营中心 硅谷的囚徒呼叫中心 客户服务 百度AI接口 语音系统 Win7旗舰版

1、获取当前年月日时分秒

# -*- encoding=utf-8 -*-
import datetime
now = datetime.datetime.now()
print("now:{}".format(now))
year = now.year
print("year:{}".format(year))
month = now.month
print("month:{}".format(month))
day = now.day
print("day:{}".format(day))
hour = now.hour
print("hour:{}".format(hour))
minute = now.minute
print("minute:{}".format(minute))
second = now.second
print("second:{}".format(second))

2、datetime转为string

# -*- encoding=utf-8 -*-
import datetime
now = datetime.datetime.now()
print('type:{}'.format(type(now)))
print('now datetime:{}'.format(now))
now_string = now.strftime('%Y-%m-%d %H:%M:%S')
print('type:{}'.format(type(now_string)))
print('now string:{}'.format(now_string))

3、string转为datetime

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:51:26'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('type:{}'.format(type(time_date)))
print(time_date)

4、时间相加

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始时间:\t\t\t\t{}'.format(time_date))
add_info = datetime.timedelta(days=1, hours=2, minutes=3, seconds=4)
add_end = time_date + add_info
print('加上1天2个小时3分钟4秒后:\t{}'.format(add_end))

 5、时间相减

①两个时间差

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始时间:\t{}'.format(time_date))
time_str = '2021-05-29 12:12:12'
time_date2 = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始时间2:\t{}'.format(time_date2))
time_date3 = time_date2 - time_date
print('时间差:{}'.format(time_date3))

②减去1天2个小时3分钟4秒(加负数)

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始时间:\t\t\t\t{}'.format(time_date))
add_info = datetime.timedelta(days=-1, hours=-2, minutes=-3, seconds=-4)
add_end = time_date + add_info
print('减去1天2个小时3分钟4秒后:\t{}'.format(add_end))

以上就是Python datetime模块的使用示例的详细内容,更多关于Python datetime模块的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
  • 一篇文章带你了解python标准库--datetime模块
  • python标准库之time模块的语法与简单使用
  • python常见模块之OS模块和time模块
  • Python学习之time模块的基本使用
  • 一篇文章带你了解python标准库--time模块

标签:山西 山西 济南 长沙 安康 海南 崇左 喀什

巨人网络通讯声明:本文标题《Python datetime模块的使用示例》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266