在 Python 中获取当前日期可以使用 datetime.today() 或 date.today() 函数,分别返回包含当前日期和时间的 datetime 对象或表示当前日期的 date 对象。date 对象可以进一步提取年、月、日属性,如 datetime.today().year、datetime.today().month 和 datetime.today().day。

在 Python 中,你可以使用 datetime 模块轻松地获取当前日期。
datetime.today()
datetime.today() 函数返回一个包含当前日期和时间的 datetime 对象。你可以使用 date() 属性从该对象中提取日期部分。
<code class="python">from datetime import datetime current_date = datetime.today().date() print(current_date) # 输出:yyyy-mm-dd</code>
date.today()
date 模块提供了 date.today() 函数,直接返回一个表示当前日期的 date 对象。
<code class="python">import date current_date = date.today() print(current_date) # 输出:yyyy-mm-dd</code>
如果你需要获取当前日期的其他部分(如年、月、日),可以使用 datetime 或 date 对象的属性:
立即学习“Python免费学习笔记(深入)”;
year:返回年份month:返回月份day:返回日期<code class="python">from datetime import datetime current_date = datetime.today() year = current_date.year month = current_date.month day = current_date.day print(year, month, day) # 输出:yyyy mm dd</code>
以上就是python如何获得当前日期的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号