python获取本机时间
时间: 2023-10-19 12:08:48 浏览: 44
在 Python 中获取本机时间可以使用内置的 `datetime` 模块。以下是获取当前时间的示例代码:
```python
import datetime
now = datetime.datetime.now()
print("当前时间:", now)
```
输出结果类似于:
```
当前时间: 2021-08-26 10:15:23.398694
```
你也可以通过 `strftime()` 方法将时间按照指定的格式输出:
```python
import datetime
now = datetime.datetime.now()
print("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
```
输出结果类似于:
```
当前时间: 2021-08-26 10:15:23
```
其中 `%Y` 表示年份,`%m` 表示月份,`%d` 表示日期,`%H` 表示小时,`%M` 表示分钟,`%S` 表示秒数。
相关问题
Python 怎么获取北京时间而不是本机时间
要获取北京时间,可以使用 Python 的 datetime 和 pytz 模块。下面是一个示例代码:
```python
import datetime
import pytz
# 设置北京时区
beijing_tz = pytz.timezone('Asia/Shanghai')
# 获取当前的本地时间
local_time = datetime.datetime.now()
# 将本地时间转换为北京时间
beijing_time = local_time.astimezone(beijing_tz)
# 输出北京时间
print(beijing_time)
```
输出的时间将会是当前的北京时间。请注意,要使用 pytz 模块,需要先使用 pip 安装它。
Python获取时间
以下是两种Python获取当前时间的方法:
1. 使用datetime模块获取当前时间:
```python
import datetime
current_time = datetime.datetime.now()
print("当前时间:", current_time)
```
2. 使用time模块获取当前时间的时间戳和可读格式:
```python
import time
# 获取当前时间的时间戳
timestamp = time.time()
# 将时间戳转换为可读格式
current_time = time.ctime(timestamp)
print("当前时间:", current_time)
```