datetime — Basic date and time types:https://docs.python.org/3.8/library/datetime.html

dateutil --- powerful extensions to datetime:https://dateutil.readthedocs.io/en/stable/index.html

Python time 和 datetime 的常用转换处理:https://www.cnblogs.com/lxmhhy/p/6030730.html

  • datetime 转 timestamp
  • datetime 转 时间字符串
  • timestamp 转 datetime
  • timestamp 转 时间字符串
  • 时间字符串 转 datetime
  • 时间字符串 转 timestamp

对于这三者的转换,python2和python3是不同的,因为在python3中新增一些实例方法,能够很方便的实现这些类型之间的转换。

如果需要python2的类型转换请移步这些文章:
python --- 时间与时间戳之间的转换:https://blog.csdn.net/google19890102/article/details/51355282
Python 字符串、时间戳、datetime 时间相关转换:https://blog.csdn.net/Data_Ada/article/details/72900019

简单介绍下,datetime 和 time 中常用的方法

  • datetime.datetime.strptime(string, format)。类方法,作用是根据指定的format(格式),将字符串转换成datetime.datetime实例对象。
  • datetime.datetime.strftime(format): 实例方法,作用就是根据指定的format(格式),将datetime.datetime实例对象转换成时间字符串。
  • datetime.datetime.timestamp(): 实例方法,作用就是将datetime.datetime实例对象转换成时间戳。
  • datetime.fromtimestamp(timestamp, tz=None):类方法,作用是将时间戳转换成datetime.datetime对象。
  • time.strptime(string, format)。类方法,作用是根据指定的format(格式)将时间字符串转换成time.struct_time对象。
  • time.strftime(format, string)。类方法,作用是根据指定的format(格式,)将time.struct_time对象转换成时间字符串。
  • time.localtime(timestamp)。类方法,作用是将时间戳转换成本地时间的time.struct_time对象。若要转换成UTC的time.struct_time对象则使用time.gtime()。
  • time.mktime(t)。类方法,time.localtime()的逆函数,因为作用正好相反。其作用是将time.struct_time对象转换成时间戳。

示例:

# 把 datetime 转成 字符串
def datetime_toString(dt):return dt.strftime("%Y-%m-%d-%H")# 把 字符串 转成 datetime
def string_toDatetime(string):return datetime.strptime(string, "%Y-%m-%d-%H")# 把 字符串 转成 时间戳形式
def string_toTimestamp(strTime):return time.mktime(string_toDatetime(strTime).timetuple())# 把 时间戳 转成 字符串形式
def timestamp_toString(stamp):return time.strftime("%Y-%m-%d-%H", tiem.localtime(stamp))# 把 datetime类型 转成 时间戳形式
def datetime_toTimestamp(dateTim):return time.mktime(dateTim.timetuple())

datetime 转 timestamp

直接使用 datetime 模块中 datetime类 的 timestamp() 实例方法。

import datetime
import timedt = datetime.datetime.now()
ts = dt.timestamp()
print(f'{type(dt)} : {dt}')
print(ts)

datetime 转 时间字符串

直接使用 datetime 模块中的 datetime类 的 strftime() 实例方法即可。

import datetime
import timedt = datetime.datetime.now()# 根据此格式来解析datetime.datetime()对象为时间字符串
format_string = '%Y-%m-%d %H:%M:%S'print(f'{type(dt)} : {dt}')
print(dt.strftime(format_string))

timestamp 转 datetime

import datetime
import timets = 1568172006.68132  # 时间戳
dt = datetime.datetime.fromtimestamp(ts)
print(dt)

timestamp 转 时间字符串

  1. 如果使用 time 模块,转换必须通过 time.struct_time对象作为桥梁。

  2. 如果使用 datetime 模块,先转成 datetime.datetime 对象,再转成时间字符串。

示例代码:

import datetime
import time# 方法 1
ts = 1568172006.68132                # 时间戳
format_string = '%Y-%m-%d %H:%M:%S'  # 根据此格式来时间戳解析为时间字符串
# 时间戳转time.struct_time
ts_struct = time.localtime(ts)
# time.struct_time 转时间字符串
date_string = time.strftime(format_string, ts_struct)print(date_string)  # '2019-09-11 11:20:06'# 方法 2
dt = datetime.datetime.fromtimestamp(ts)
date_string = dt.strftime(format_string)

时间字符串 转 datetime

只需要使用 datetime模块 中的 datetime类 的 strptime(date_string, format)类方法即可。
这个方法的作用就是:根据指定的 format 格式将时间字符串 date_string,转换成 datetime.datetime()对象。

import datetime
import timedate_string = '2019-09-11 11:20:06'
# 根据此格式来解析时间字符串为datetime.datetime()对象
format_string = '%Y-%m-%d %H:%M:%S'dt = datetime.datetime.strptime(date_string, format_string)
print(dt)  # datetime.datetime(2019, 9, 11, 11, 20, 6)

时间字符串 转 timestamp

  1. 方法 1:如果使用 time 模块,转换必须通过 time.struct_time 对象作为桥梁。

  2. 方法 2:如果使用 datetime 模块,先转成 datetime.datetime 对象,再转成 timestamp。

示例代码:

import datetime
import time# 方法 1
date_string = '2019-09-11 11:20:06'
format_string = '%Y-%m-%d %H:%M:%S'  # 根据此格式来解析时间字符串为time()对象# 时间字符串转 time.struct_time
ts_struct = time.strptime(date_string, format_string)
# time.struct_time 转时间戳
ts = time.mktime(ts_struct)
print(ts)  # 1568172006.0# 方法 2
dt = datetime.datetime.strptime(date_string, format_string)
ts = dt.timestamp()

日期输出格式化

所有日期、时间的 api 都在 datetime 模块内。

1. datetime  ----->  string

import datetimeif __name__ == '__main__':now = datetime.datetime.now()t = now.strftime('%Y-%m-%d %H:%M:%S')print(type(t), t)# 结果:<class 'str'> 2019-12-13 14:08:35

strftime 是 datetime类 的实例方法。

import time

time.strftime

"""
strftime(format[, tuple]) -> stringConvert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.Commonly used format codes:%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.Other codes may be available on your platform.  See documentation for
the C library strftime function.
"""

time.strptime

"""
strptime(string, format) -> struct_timeParse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).Commonly used format codes:%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.Other codes may be available on your platform.  See documentation for
the C library strftime function.
"""

更多 time() 模块函数,可以查看 time() 模块

2. string  ----->  datetime

import datetimeif __name__ == '__main__':t_str = '2012-03-05 16:26:23'd = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')print(type(d), d)# 结果:<class 'datetime.datetime'> 2012-03-05 16:26:23

strptime 是 datetime类 的 静态方法。

日期比较操作

在 datetime 模块中有 timedelta类,这个类的对象用于表示一个时间间隔,比如两个日期或者时间的差别。

构造方法:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

所有的参数都有默认值0,这些参数可以是int或float,正的或负的。

可以通过 timedelta.days、tiemdelta.seconds 等获取相应的时间值。

timedelta类的实例支持加、减、乘、除等操作,所得的结果也是 timedelta类 的 实例。比如:

year = timedelta(days=365)
ten_years = year *10
nine_years = ten_years - year

同时,date、time 和 datetime 类也支持与 timedelta 的加、减运算。

datetime1 = datetime2 +/- timedelta
timedelta = datetime1 - datetime2

这样,可以很方便的实现一些功能。

1. 两个日期相差多少天。

import datetimeif __name__ == '__main__':d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')delta = d1 - d2        print(type(delta), delta.days)# 结果:<class 'datetime.timedelta'> 3

2. 今天的 n 天后的日期。

import datetimeif __name__ == '__main__':now = datetime.datetime.now()delta = datetime.timedelta(days=3)n_days = now + deltaprint(n_days.strftime('%Y-%m-%d %H:%M:%S'))# 结果:2019-12-16 14:14:06

示例代码:

import datetimenow = datetime.datetime.now()
print(now)# 将日期转化为字符串 datetime => string
print(now.strftime('%Y-%m-%d %H:%M:%S'))t_str = '2012-03-05 16:26:23'
# 将字符串转换为日期 string => datetime
d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
print(d)# 在datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日#期或者时间的差别。# 计算两个日期的间隔
d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
delta = d1 - d2
print(delta.days)
print(delta)# 今天的n天后的日期。
now = datetime.datetime.now()
delta = datetime.timedelta(days=3)
n_days = now + delta
print(n_days.strftime('%Y-%m-%d %H:%M:%S'))# 结果
# 2019-12-13 14:23:35.819567
# 2019-12-13 14:23:35
# 2012-03-05 16:26:23
# 3
# 3 days, 0:00:00
# 2019-12-16 14:23:35

示例代码 :

import time
import datetimeif __name__ == '__main__':now_time = datetime.datetime.now()  # 当前时间now_time_mk = time.mktime(now_time.timetuple())  # 当前时间戳current_month = now_time.month# 下月第一天最后一秒时间if current_month == 12:        next_mouth_first_day = datetime.datetime(now_time.year + 1, 1, 1, 23, 59, 59)else:next_mouth_first_day = datetime.datetime(now_time.year, current_month + 1, 1, 23, 59, 59)# 当前月最后一天current_month_last_day = next_mouth_first_day - datetime.timedelta(days=1)# 当前月第一天current_month_first_day = datetime.date(now_time.year, now_time.month, 1)# 前一月最后一天pre_month_last_day = current_month_first_day - datetime.timedelta(days=1)# 前一月第一天pre_month_first_day = datetime.date(pre_month_last_day.year, pre_month_last_day.month, 1)print(next_mouth_first_day)print(current_month_last_day)print(current_month_first_day)print(pre_month_last_day)print(pre_month_first_day)'''
结果:
2020-01-01 23:59:59
2019-12-31 23:59:59
2019-12-01
2019-11-30
2019-11-01
'''

Python 日期 的 加减 等 操作相关推荐

  1. python 月份加减,Python日期的加减等操作的示例

    本文介绍了Python日期的加减等操作的示例,分享给大家,也给自己留个笔记 1. 日期输出格式化 所有日期.时间的api都在datetime模块内. 1. datetime => string ...

  2. Python日期的加减等操作

    1. 日期输出格式化 所有日期.时间的api都在datetime模块内. 1. datetime => string now = datetime.datetime.now() now.strf ...

  3. python datetime 加一个月_Python日期的加减等操作的示例

    本文介绍了Python日期的加减等操作的示例,分享给大家,也给自己留个笔记 1. 日期输出格式化 所有日期.时间的api都在datetime模块内. 1. datetime => string ...

  4. Python日期的加减

    一.timedelta #Python的timedelta可以处理时间的加减import datetime sdate = datetime.datetime.strptime('2019.01.05 ...

  5. python日期加减一年_Python日期的加减等操作

    原文:https://www.cnblogs.com/vampirejt/p/4159267.html 1. 日期输出格式化 所有日期.时间的api都在datetime模块内. 1. datetime ...

  6. [笔试] 搜狗校招哈尔滨,武汉站 - 实现加减乘操作

    已知计算机有以下原子操作 1. 赋值操作:b = a; 2. ++a和a+1; 3.for( ){ ***}有限循环: 4.操作数只能为0或者正整数: 5.定义函数 实现加减乘操作 #include ...

  7. 用js进行日期的加减

    如题,开始查了查js的使用文档,但没发现可以直接用的函数,于是就想自己写函数来着,这就要涉及到每个月天数的判断,如果是2月份的话,还要涉及到闰年的判断,虽然不复杂但我想js应该不会这么低级,于是查了下 ...

  8. 如何用js进行日期的加减(天数)?

    如何用js进行日期的加减(天数)? HTML部分 <div class="col-md-2"><div class="form-group"& ...

  9. oracle中那个日期怎么相减_oracle日期时间加减规则

    1.日期的加减都是以天为单位的 SELECT to_date('2016-07-05 13:10:00','yyyy-mm-dd hh24:mi:ss') + 1 FROM dual; 结果:2016 ...

最新文章

  1. 上热搜了!“学了Python6个月,竟然找不到工作!”
  2. LeetCode题组:第169题-多数元素
  3. python - socket模块1
  4. Pycharm-列出代码结构
  5. MyBatis mapper 注解过程中通过 LanguageDriver 实现动态 SQL
  6. 隐藏网页文件的后缀(IIS测试通过)!
  7. 将DataSet中的操作更新到Access数据库
  8. 初始化与赋值哪个效率高?
  9. cdr如何制作图表?
  10. 2.晶晨A311D-编译Ubuntu/Debian固件
  11. ajax.post传输数据,ajax POST方式数据传递
  12. 机会是留给有准备的人的
  13. Unity 画折线图
  14. python新技术_2020年令人期待的Python新功能
  15. Python下载微信公众号文章和图片保存至本地
  16. 力扣:我的日程安排表I
  17. selenium实战 登录后跳转到外部网站,添加多个数据 (UI-0107)分享(白月黑羽网站selenium自动化学习)
  18. 华夫饼为什么不松软_只需半个小时,教你轻松制作松软“华夫饼”,健康美味无添加...
  19. Java,Android,窥探组合的用法。AndroidUI组合设计模式,Java组合设计模式
  20. 全球电力行业十大网络安全攻击事件

热门文章

  1. 论文小综 | Pre-training on Graphs
  2. PaddlePaddle预训练模型大合集
  3. 【Java】函数式编程
  4. 国科大高级人工智能5-RNN/LSTM/GRU/集束搜索/attention
  5. 浅谈Spring IOC和DI及Spring工厂类
  6. JS高级学习笔记(6)- 事件循环
  7. zbb20170228_spring_tdt
  8. leancloud的技术面试指南
  9. PHP环境安全性能检查
  10. 【转载】贝叶斯决策论