python获取当前时间
时间: 2023-06-22 17:47:36 浏览: 72
在Python中,可以使用内置的`datetime`模块来获取当前的时间。以下是获取当前时间的代码示例:
```python
import datetime
# 获取当前日期和时间
now = datetime.datetime.now()
# 获取当前年份
year = now.year
# 获取当前月份
month = now.month
# 获取当前天数
day = now.day
# 获取当前小时数
hour = now.hour
# 获取当前分钟数
minute = now.minute
# 获取当前秒数
second = now.second
# 打印当前日期和时间
print("当前时间为:", now)
# 打印当前年份
print("当前年份为:", year)
# 打印当前月份
print("当前月份为:", month)
# 打印当前天数
print("当前天数为:", day)
# 打印当前小时数
print("当前小时数为:", hour)
# 打印当前分钟数
print("当前分钟数为:", minute)
# 打印当前秒数
print("当前秒数为:", second)
```
输出结果类似于:
```
当前时间为: 2021-08-09 13:45:30.123456
当前年份为: 2021
当前月份为: 8
当前天数为: 9
当前小时数为: 13
当前分钟数为: 45
当前秒数为: 30
```
注意:以上示例代码中的`123456`是微秒数,如果不需要可以省略。
相关问题
python 获取当前时间
要在Python中获取当前时间,你可以使用`datetime`模块。具体方法是使用`datetime`模块的`datetime`类,并调用其`now()`方法来获取当前时间。
下面是一个示例代码,演示如何获取当前时间:
```python
from datetime import datetime
# 获取当前时间
current_time = datetime.now()
# 打印当前时间
print(current_time)
```
上述代码将打印出当前的日期和时间,格式类似于`2022-01-01 10:30:00.123456`。
你也可以使用`strftime()`方法来格式化输出的时间,以满足你的需求。例如,如果你只想获取当前时间的小时和分钟,可以使用以下代码:
```python
current_time = datetime.now().strftime("%H:%M")
print(current_time)
```
上述代码将打印出当前时间的小时和分钟,格式类似于`10:30`。
希望能对你有所帮助!如果你还有其他问题,请随时提问。
python获得当前时间
要在Python中获得当前时间,有多种方法可以实现。
一种方法是使用datetime模块。可以使用datetime.now()函数获取当前时间。示例代码如下:
```
import datetime
current_time = datetime.datetime.now()
print("current_time:", str(current_time))
```
执行结果类似于:
```
current_time: 2021-08-11 11:48:11.122521
```
另一种方法是使用time模块的strftime()函数格式化输出系统时间。示例代码如下:
```
import time
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
```
这将输出当前时间的格式化结果,例如:
```
2021-08-11 11:48:11
```
以上是获取当前时间的两种常见方法。你可以根据需要选择适合你的应用程序的方法。