在 Python 中获取当前日期有两种方法:使用 datetime.date.today() 直接获取当前日期(不含时间部分);使用 datetime.datetime.now().date() 获取当前日期和时间,然后提取日期部分。

如何用 Python 获取当前日期
获取当前日期的两种方法:
1. datetime.date.today()
此方法直接返回当前日期的 datetime.date 对象,该对象只包含日期部分,不包括时间部分。
立即学习“Python免费学习笔记(深入)”;
<code class="python">import datetime current_date = datetime.date.today() print(current_date) # 输出:2023-03-08</code>
2. datetime.datetime.now().date()
此方法先获取当前日期和时间,然后只提取日期部分。
<code class="python">import datetime current_datetime = datetime.datetime.now() current_date = current_datetime.date() print(current_date) # 输出:2023-03-08</code>
以上就是python如何获取当前日期的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号