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

我在用着:

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

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

有没有那么简单的方法可以做到这一点?

I’m using:

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

to return today’s date in the YYYY-MM-DD format.

Is there a less crude way to achieve this?


回答 0

您可以使用strftime

from datetime import datetime

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

此外,对于任何还在末尾寻找零填充的小时,分​​钟和秒的人:(Gabriel Staples评论)

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

You can use 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)

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

回答 1

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

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

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

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

回答 2

如果您想记住有趣的代码,那么日期时间就是很好的选择。您不喜欢简单吗?

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

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

做吧pip install arrow

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

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

>>> 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.

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


回答 3

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

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

请注意,如果您还需要标准格式的时间,则此方法也适用于datetime对象。

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

I always use the isoformat() function for this.

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'

回答 4

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

潘达斯

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

import pandas as pd

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

作为python datetime对象,

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

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

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'

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

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

除了之外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)

如果要使您的时间戳记时区知道,请将时区传递给tz参数。

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

如果您使用摆锤,则有一些有趣的选择。您可以使用来获取当前时间戳记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'))

此外,您也可以直接获取tomorrow()yesterday()的日期,而无需执行任何其他的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'))

有各种可用的格式设置选项。

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'

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

PANDAS

You can use pd.to_datetime from the pandas library. Here are various options, depending on what you want returned.

import pandas as pd

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

As a python datetime object,

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.

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

Aside from to_datetime, you can directly instantiate a Timestamp object using,

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 tz argument.

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().

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.

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'

回答 5

答案很晚,但是您可以使用:

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

Very late answer, but you can use:

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

回答 6

您可以使用,

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

You can use,

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

回答 7

我喜欢这个,因为这很简单,但是可能效率不高且有问题。如果您要一个高度防错的程序,则必须检查shell命令的退出代码。

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

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 strongly error-proof program.

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。