在Python中以YYYY-MM-DD获取今天的日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32490629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:40:18  来源:igfitidea点击:

Getting today's date in YYYY-MM-DD in Python?

pythondatetimepython-datetime

提问by Pyderman

I'm using:

我正在使用:

str(datetime.datetime.today()).split()[0]

to return today's date in the YYYY-MM-DDformat.

YYYY-MM-DD格式返回今天的日期。

Is there a less crude way to achieve this?

有没有更简单的方法来实现这一目标?

采纳答案by diegueus9

You can use strftime:

您可以使用strftime

from datetime import datetime

datetime.today().strftime('%Y-%m-%d')

Additionally, for anyone also looking for a zero-padded Hour, Minute, and Second at the end: (Comment by Gabriel Staples)

此外,对于任何也在最后寻找零填充的小时、分钟和秒的人:(Gabriel Staples评论)

datetime.today().strftime('%Y-%m-%d-%H:%M:%S')

回答by Bill Bell

Datetime is just lovely if you like remembering funny codes. Wouldn't you prefer simplicity?

如果您喜欢记住有趣的代码,Datetime 就很可爱。你不喜欢简单吗?

>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
'2017-02-17'

This module is clever enough to understand what you mean.

这个模块足够聪明,可以理解你的意思

Just do pip install arrow.

就做pip install arrow

Addendum: In answer to those who become exercised over this answer let me just say that arrow represents one of the alternativeapproaches to dealing with dates in Python. That's mostly what I meant to suggest.

附录:为了回答那些对这个答案感到困惑的人,我只想说箭头代表了在 Python 中处理日期的另一种方法。这主要是我想建议的。

回答by kmonsoor

You can use datetime.date.today()and convert the resulting datetime.dateobject to a string:

您可以使用datetime.date.today()结果datetime.date对象并将其转换为字符串:

from datetime import date
today = str(date.today())
print(today)   # '2017-12-26'

回答by plhn

I prefer this, because this is simple, but maybe somehow inefficient and buggy. You must check the exit code of shell command if you want a stronglyerror-proof program.

我更喜欢这个,因为这很简单,但也许效率低下且有问题。如果你想要一个强大的防错程序,你必须检查 shell 命令的退出代码。

os.system('date +%Y-%m-%d')

回答by JdH

I always use the isoformat()function for this.

我总是isoformat()为此使用该功能。

from datetime import date    
today = date.today().isoformat()
print(today) # '2018-12-05'

Note that this also works on datetime objects if you need the time in standard format as well.

请注意,如果您还需要标准格式的时间,这也适用于日期时间对象。

from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'

回答by cs95

Other answers suggest the use of python's datetime.datetime, but as @Bill Bell said, there are other libraries that offer simpler datetimeinterfaces either as a service or as part of a larger ecosystem of APIs. Here are two such libraries that make working with datetimesvery simple.

其他答案建议使用 python 的datetime.datetime,但正如@Bill Bell 所说,还有其他库提供更简单的datetime接口作为服务或作为更大的 API 生态系统的一部分。这里有两个这样的库,它们使工作变得datetimes非常简单。

PANDAS

熊猫

You can use pd.to_datetimefrom the pandaslibrary. Here are various options, depending on what you want returned.

您可以pd.to_datetime熊猫库中使用。这里有各种选项,具体取决于您想要返回的内容。

import pandas as pd

pd.to_datetime('today')  # pd.to_datetime('now')
# Timestamp('2019-03-27 00:00:10.958567')

As a python datetimeobject,

作为 python日期时间对象,

pd.to_datetime('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 50, 42, 587629)

As a formatted date string,

作为格式化的日期字符串,

pd.to_datetime('today').isoformat()
# '2019-04-18T04:03:32.493337'

# Or, `strftime` for custom formats.
pd.to_datetime('today').strftime('%Y-%m-%d')
# '2019-03-27'

To get just the date from the timestamp, call Timestamp.date.

要仅从时间戳中获取日期,请调用Timestamp.date

pd.to_datetime('today').date()
# datetime.date(2019, 3, 27)

Aside from to_datetime, you can directly instantiate a Timestampobject using,

除了to_datetime,您还可以Timestamp使用以下方法直接实例化对象,

pd.Timestamp('today')  # pd.Timestamp('now')
# Timestamp('2019-04-18 03:43:33.233093')

pd.Timestamp('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 53, 46, 220068)

If you want to make your Timestamp timezone aware, pass a timezone to the tzargument.

如果您想让 Timestamp 时区知道,请将时区传递给tz参数。

pd.Timestamp('now', tz='America/Los_Angeles')
# Timestamp('2019-04-18 03:59:02.647819-0700', tz='America/Los_Angeles')


PENDULUM

If you're working with pendulum, there are some interesting choices. You can get the current timestamp using now()or today's date using today().

如果您正在使用pendulum,那么有一些有趣的选择。您可以使用 获取当前时间戳now()或使用今天的日期today()

import pendulum 

pendulum.now()
# DateTime(2019, 3, 27, 0, 2, 41, 452264, tzinfo=Timezone('America/Los_Angeles'))

pendulum.today()
# DateTime(2019, 3, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

Additionally, you can also get tomorrow()or yesterday()'s date directly without having to do any additional timedelta arithmetic.

此外,您还可以直接获取tomorrow()oryesterday()的日期,而无需进行任何额外的 timedelta 算术。

pendulum.yesterday()
# DateTime(2019, 3, 26, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

pendulum.tomorrow()
# DateTime(2019, 3, 28, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

There are various formatting options available.

有多种格式选项可用。

pendulum.now().to_date_string()
# '2019-03-27'

pendulum.now().to_formatted_date_string()
# 'Mar 27, 2019'

pendulum.now().to_day_datetime_string()
# 'Wed, Mar 27, 2019 12:04 AM'

回答by Mohideen bin Mohammed

You can use,

您可以使用,

>>> from datetime import date
>>> date.today().__str__()
'2019-10-05'

回答by CONvid19

import time
today = time.strftime("%Y-%m-%d")
# 2020-02-14