首页 > 编程语言 >Python 日期 的 加减 等 操作

Python 日期 的 加减 等 操作

时间:2022-10-10 23:06:51浏览次数:69  
标签:-% string format Python 加减 .% datetime 日期 time

 

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 的常用转换处理​

 

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

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

简单介绍下,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 time

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

 

 

datetime 转 时间字符串

 

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

import datetime
import time

dt = 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 time

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

 

 

timestamp 转 时间字符串

 

  1. 如果使用 time 模块,转换必须通过 time.struct_time对象作为桥梁。
  2. Python 日期 的 加减 等 操作_字符串

  3. 如果使用 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 time

date_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. Python 日期 的 加减 等 操作_python_02

  3. 方法 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 datetime


if __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]) -> string

Convert 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_time

Parse 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 datetime


if __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 datetime


if __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 datetime


if __name__ == '__main__':
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-16 14:14:06

示例代码:

import datetime

now = 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 datetime


if __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
'''

 

 

 



标签:-%,string,format,Python,加减,.%,datetime,日期,time
From: https://blog.51cto.com/csnd/5745418

相关文章

  • 怎么可以少了“雪融融”呢?python在画一个雪蓉蓉陪着“冰墩墩”
    公众号ID|ComputerVisionGzq学习群|扫码在主页获取加入方式计算机视觉研究院专栏作者:Edison_G冬奥会如火如荼的举行中,吉祥物之一的冰墩墩特别抢手!身为程序员,已经拥有一个“虚......
  • LMS Virtual.Lab二次开发:声学仿真理论基础准备(Python)
    1、简介采用LMSVirtual.LabAcoustics声学软件,可以直接打开CATIAV5的设计模型、或者间接导入其它CAD软件的三维模型,实现从声学模型创建、复杂边界条件加载、快速求解计算......
  • python词云剔除非有效词
    title:python词云剔除非有效词excerpt:python爬虫小作业2.0tags:[python,词云,爬虫]categories:[学习,python]index_img:https://picture-store-repository.......
  • CentOS7下安装python3.8卸载3.6
    title:CentOS7下安装python3.8卸载3.6excerpt:VM记得拍快照!拍快照!快照!tags:[语音识别,kaldi,python3,python2,centos7]categories:[学习,python][学习,语......
  • python的基本运用
    python基础Python语言是一种解释型、面向对象、动态数据类型的高级程序设计语言开发者:GuidovanRossum(人称龟叔)基本概念1.变量变量名必须是大小写英文字母、数字或下......
  • Python 应用之求 100 以内的奇数和
    在数学中,我们需要用到很多求和的办法,比如说求1至100的和,还有100以内的所有偶数和和所有奇数和,如果我们慢慢地计算是不是很浪费时间,还容易出错。其实通过Python就可......
  • 【Azure 应用服务】Python Function App重新部署后,出现 Azure Functions runtime is u
    问题描述PythonFunctionApp重新部署后,出现AzureFunctionsruntimeisunreachable错误 问题解答在FunctionApp的门户页面中,登录Kudu站点(https://<yourfunction......
  • python中reload(sys)详解
    问题python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报错UnicodeDecodeError:‘ascii’codeccan’tdecodebyte0x??inposition1:o......
  • python opencv画矩形框保存xml和读取显示
     参考图书馆空位检测(行人+空位对比)https://www.cnblogs.com/gooutlook/p/16192389.html  使用到的原始图像       1鼠标选择画框API_draw.py......
  • python中函数教程
    函数的基本概念1.什么是函数?函数相当于一种工具,就是把一串代码装到一起,我们下次需要用的这个功能的时候可以直接使用函数相当于是工具(具有一定功能)不用函数修理工需......