python获取当前日期不要微秒
时间: 2023-07-06 19:36:19 浏览: 54
在Python中获取当前日期可以使用datetime模块中的date类。
可以按照以下代码获取当前日期:
```python
from datetime import datetime
# 获取当前日期,不要微秒
today = datetime.now().date()
print("当前日期为:", today)
```
输出结果类似于:
```
当前日期为: 2021-08-18
```
需要注意的是,这里使用datetime.now()获取当前日期和时间,然后使用date()方法仅获取日期部分,去掉了微秒。
相关问题
python获取当前时间
在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`来获取当前时间。
示例代码:
```python
import datetime
# 获取当前时间
now = datetime.datetime.now()
# 输出当前时间
print("当前时间为:", now)
```
输出结果:
```
当前时间为: 2022-03-16 20:34:59.123456
```
其中,`now()`函数返回的是一个`datetime`对象,包括年、月、日、时、分、秒、微秒等信息。如果只需要获取当前时间的某个部分,可以使用`year`、`month`、`day`、`hour`、`minute`、`second`等属性进行访问。例如:
```python
# 获取当前年份
year = now.year
print("当前年份为:", year)
# 获取当前月份
month = now.month
print("当前月份为:", month)
# 获取当前日
day = now.day
print("当前日为:", day)
# 获取当前小时
hour = now.hour
print("当前小时为:", hour)
# 获取当前分钟
minute = now.minute
print("当前分钟为:", minute)
# 获取当前秒数
second = now.second
print("当前秒数为:", second)
# 获取当前微秒数
microsecond = now.microsecond
print("当前微秒数为:", microsecond)
```
输出结果:
```
当前年份为: 2022
当前月份为: 3
当前日为: 16
当前小时为: 20
当前分钟为: 34
当前秒数为: 59
当前微秒数为: 123456
```