> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/python/python-xiao-ji-qiao/datatime-ku-ji-suan-dang-qian-shi-jian-qi-ta-shi-jian-yun-suan.md).

# datatime库计算当前时间||其他时间运算

## python之datatime模块计算当前时间的其他时间相关运算

#### 1、计算当前时间

```python
import datetime

print(datetime.datetime.now())
# 2022-07-25 19:52:27.479555

# 格式化时间
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 19:52:27
```

#### 2、计算当前时间的前一天/后一天

```python
import datetime

# 当前时间
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 19:57:51

# 当前时间的后一天
print((datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-26 19:57:51

# 当前时间的前一天
print((datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-24 19:57:51
```

#### 3、计算当前时间的前一小时/后一小时

```python
import datetime

# 当前时间
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 20:00:20

# 当前时间的前一小时
print((datetime.datetime.now() + datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 21:00:20

# 当前时间的后一小时
print((datetime.datetime.now() - datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 19:00:20
```

#### 4、计算当前时间的前一分钟/后一分钟

```python
import datetime

# 当前时间
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 20:03:41

# 当前时间的前一分钟
print((datetime.datetime.now() + datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 20:04:41

# 当前时间的后一分钟
print((datetime.datetime.now() - datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 20:02:41
```

#### 5、计算当前时间的前一秒/后一秒

```python
import datetime

# 当前时间
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 20:03:41

# 当前时间的前一分钟
print((datetime.datetime.now() + datetime.timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 20:04:41

# 当前时间的后一分钟
print((datetime.datetime.now() - datetime.timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2022-07-25 20:02:41
```

#### 6、计算两个时间不同天数的时间差

```python
from datetime import datetime

time_1 = '2020-03-02 15:00:00'
time_2 = '2020-03-03 16:00:00'

time_1_struct = datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S")
time_2_struct = datetime.strptime(time_2, "%Y-%m-%d %H:%M:%S")

print(time_1_struct)

print(time_2_struct)

total_seconds = (time_2_struct - time_1_struct).total_seconds()
print('两个时间（不同天）的相差的秒数：', int(total_seconds))

min_sub = total_seconds / 60
print('两个时间（不同天）的相差的分钟数：', int(min_sub))

min_days = (datetime(year=2010, month=3, day=1) - datetime(year=2010, month=2, day=1)).days
print('两个时间（不同天）的相差的天数：', min_days)
```

#### 7、获取所在当月的日期

```python
import datetime

present_date = datetime.datetime.now().day

print('本月当前日期：', present_date)
# 本月当前日期： 26
```

#### 8、获取所在当前月份

```python
import datetime

present_month = datetime.datetime.now().month


print('当前月份：', present_month)
# 当前月份： 7
```

#### 9、获取所在当前年份

```python
import datetime

now = datetime.datetime.now()
print('当前时间：', now)
# 当前时间： 2022-07-26 11:15:30.104951
present_year = datetime.datetime.now().year
print('当前年份：', present_year)
# 当前年份： 2022
```

#### 10、获取当前时间的三天前的此时

```python
import datetime

now = datetime.datetime.now()
print('当前时间：', now)
# 当前时间： 2022-07-26 11:19:22.759510

three_days_ago = now + datetime.timedelta(-3)
print('当前时间三天前此时：', three_days_ago)
# 当前时间三天前此时： 2022-07-23 11:19:22.759510
```

#### 11、获取当前时间三天n分n秒前的时间

```python
import datetime

now = datetime.datetime.now()
print('当前时间：', now)
# 当前时间： 2022-07-26 11:24:39.188088

three_days_ago = now + datetime.timedelta(-3)
print('当前时间三天前此时：', three_days_ago)
# 当前时间三天前此时： 2022-07-23 11:24:39.188088

that_time_1 = now + datetime.timedelta(days=-3, minutes=-12, seconds=0)
print('当前时间三天12分0秒前的时间：', that_time_1)
# 当前时间三天12分0秒前的时间： 2022-07-23 11:12:39.188088

that_time_2 = now + datetime.timedelta(days=-10, minutes=-20, seconds=-30)
print('当前时间10天20分30秒前的时间：', that_time_2)
# 当前时间10天20分30秒前的时间： 2022-07-16 11:04:09.188088

that_time_3 = now + datetime.timedelta(days=10, minutes=20, seconds=30)
print('当前时间的10天20分30秒后的时间：', that_time_3)
# 当前时间的10天20分30秒后的时间： 2022-08-05 11:45:09.188088
```

#### 12、获取当前时间的昨天/明天日期

```python
import datetime
from datetime import timedelta

# 获取今天日期：

# 返回datetime格式:
now = datetime.datetime.now()
print(now)
# 2022-07-26 11:58:01.523623

# 返回datetime格式：
now = datetime.datetime.now().date()
print(now)
# 2022-07-26

now = datetime.date.today()
print(now)
# 2022-07-26

# 获取昨天日期：
yesterday = now + timedelta(days=-1)
print(yesterday)
# 2022-07-25

yesterday = now - timedelta(days=1)
print(yesterday)
# 2022-07-25

# 获取明天日期
tomorrow = now + timedelta(days=1)
print(tomorrow)
# 2022-07-27
```

#### 13、获取当前时间的本周第一天和本周最后一天

```python
import datetime
from datetime import timedelta

# 获取今天日期：

# 返回datetime格式:
now = datetime.datetime.now()
print(now)
# 2022-07-26 11:58:01.523623

# 返回datetime格式：
now = datetime.datetime.now().date()
print(now)
# 2022-07-26

now = datetime.date.today()
print(now)
# 2022-07-26

# 获取本周第一天
this_week_start = now - timedelta(days=now.weekday())
print(this_week_start)
# 2022-07-25

# 获取本周最后一天
this_week_end = now + timedelta(days=6 - now.weekday())
print(this_week_end)
# 2022-07-31
```

#### 14、获取当前时间的上周第一天和上周最后一天

```python
import datetime
from datetime import timedelta

# 获取今天日期：

# 返回datetime格式:
now = datetime.datetime.now()
print(now)
# 2022-07-26 11:58:01.523623

# 返回datetime格式：
now = datetime.datetime.now().date()
print(now)
# 2022-07-26

now = datetime.date.today()
print(now)
# 2022-07-26

# 获取上周第一天
this_week_start = now - timedelta(days=now.weekday() + 7)
print(this_week_start)
# 2022-07-18

# 获取上周最后一天
this_week_end = now + timedelta(days=6 - now.weekday() + 1)
print(this_week_end)
# 2022-08-01
```

#### 15、获取当前时间的本月第一天和本月最后一天

```python
import calendar
import datetime

# 获取今天日期：

# 返回datetime格式:
now = datetime.datetime.now()
print(now)
# 2022-08-03 14:09:37.451921

# 返回datetime格式：
now = datetime.datetime.now().date()
print(now, type(now))
# 2022-08-03

now = datetime.date.today()
print(now, type(now))
# 2022-08-03

# 获取本月第一天
this_month_start = datetime.datetime(year=now.year, month=now.month, day=1).date()
print(this_month_start)
# 2022-08-01

# 获取本月最后一天
this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1]).date()
print(this_month_end)
# 2022-08-31
```

#### 16、获取当前时间的上月的第一天和上月的最后一天

```python
import calendar
import datetime

# 获取今天日期：

# 返回datetime格式:
now = datetime.datetime.now()
print(now)
# 2022-08-03 14:09:37.451921

# 返回datetime格式：
now = datetime.datetime.now().date()
print(now, type(now))
# 2022-08-03

now = datetime.date.today()
print(now, type(now))
# 2022-08-03

# 获取上月最后一天
this_month_start = datetime.datetime(year=now.year, month=now.month, day=1).date()
last_month_end = this_month_start - datetime.timedelta(days=1)
print(last_month_end)
# 2022-07-31

# 获取上月第一天
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1).date()
print(last_month_start)
# 2022-07-01
```

#### 17、获取某一日期是星期几

```python
import datetime
import calendar

# print(datetime.date(2023, 4, 13).weekday())
print(datetime.datetime.now())  # 2023-04-13 15:10:01.824637
"""
datetime模块中的方法weekday()可用于检索星期几，结果返回0-6之间的整数，用来代表“星期一”到“星期日”。
"""
print(datetime.datetime.now().weekday())  # 3

week_list = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
print(week_list[datetime.datetime.now().weekday()])  # 星期四

"""
datetime模块中的isoweekday()方法与weekday()方法的工作原理类似，最大的区别是它返回1-7之间的整数，用来代表“星期一”到“星期日”。
"""
print(datetime.datetime.now().isoweekday())  # 4

"""
直接输出日期的英文周名，使用strftime()方法。
"""
print(datetime.datetime.now().strftime("%A"))  # Thursday
"""
如果将代码中的%A改为%a，则输出的是星期几的简写。
"""
print(datetime.datetime.now().strftime("%a"))  # Thu
```

#### 拓展：

* datetime类型时间（datetime）
* 字符串类型时间（str）
* 时间戳类型时间（float）
* 时间元祖类型时间（time.struct\_time）相互转换

```python
#!/usr/bin/env python

# -*- coding:utf-8 -*-


import datetime

import time

# 日期时间字符串
st = "2017-11-23 16:10:10"
print('字符串类型 时间：{}'.format(st), '类型：{}'.format(type(st)))

# 当前日期时间
dt = datetime.datetime.now()
print('datetime类型 时间：{}'.format(dt), '类型：{}'.format(type(dt)))

# 当前时间戳
sp = time.time()
print('时间戳类型 时间：{}'.format(sp), '类型：{}'.format(type(sp)))

# 生成struct_time时间元组
sl = time.localtime()
print('时间元祖类型 时间：{}'.format(sl), '类型：{}'.format(type(sl)))

# 生成format_time格式化时间
sf = time.strftime("%Y-%m-%d %X")
print('格式化类型 时间：{}'.format(sf), '类型：{}'.format(type(sf)))

print('\n')


# 1.把datetime转成字符串
def datetime_toString(time_value: datetime):
    print("1.把datetime.datetime类型时间转成字符串类型时间: ", time_value.strftime("%Y-%m-%d %H:%M:%S"))
    print(type(time_value), '--->', type(time_value.strftime("%Y-%m-%d %H:%M:%S")), end='\n\n')


# 2.字符串转成datetime
def string_toDatetime(time_value: str):
    print("2.把字符串类型时间转成datetime类型时间: ", datetime.datetime.strptime(time_value, "%Y-%m-%d %H:%M:%S"))
    print(type(time_value), '--->', str(type(datetime.datetime.strptime(time_value, "%Y-%m-%d %H:%M:%S"))), end='\n\n')


# 3.字符串转成时间戳形式
def string_toTimestamp(time_value: str):
    print("3.把字符串类型时间转成时间戳类型时间:", time.mktime(time.strptime(time_value, "%Y-%m-%d %H:%M:%S")))
    print(type(time_value), '--->', str(type(time.mktime(time.strptime(time_value, "%Y-%m-%d %H:%M:%S")))), end='\n\n')


# 4.时间戳转成字符串形式
def timestamp_toString(time_value: float):
    print("4.把时间戳类型时间转成字符串类型时间: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_value)))
    print(str(type(time_value)), '--->', type(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_value))),
          end='\n\n')


# 5.datetime类型转时间戳形式
def datetime_toTimestamp(time_value: datetime):
    print("5.把datetime类型时间转成时间戳类型时间:", time.mktime(time_value.timetuple()))
    print(str(type(time_value)), '--->', type(time.mktime(time_value.timetuple())), end='\n\n')



# 1.把datetime转成字符串
datetime_toString(dt)

# 2.把字符串转成datetime
string_toDatetime(st)

# 3.把字符串转成时间戳形式
string_toTimestamp(st)

# 4.把时间戳转成字符串形式
timestamp_toString(sp)

# 5.把datetime类型转外时间戳形式
datetime_toTimestamp(dt)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/python/python-xiao-ji-qiao/datatime-ku-ji-suan-dang-qian-shi-jian-qi-ta-shi-jian-yun-suan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
