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

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?

This question is related to python datetime python-datetime

The answer is


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'

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.


To get day number from date is in python

for example:19-12-2020(dd-mm-yyy)order_date we need 19 as output

order['day'] = order['Order_Date'].apply(lambda x: x.day)

You can use,

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

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'

This works:

from datetime import date
today =date.today()

Output in this time: 2020-08-29

Additional:

this_year = date.today().year
this_month = date.today().month
this_day = date.today().day
print(today)
print(this_year)
print(this_month)
print(this_day)

from datetime import datetime

date = datetime.today().date()

print(date)

my code is a little complicated but I use it a lot

strftime("%y_%m_%d", localtime(time.time()))

reference:'https://strftime.org/

you can look at the reference to make anything you want for you what YYYY-MM-DD just change my code to:

strftime("%Y-%m-%d", localtime(time.time()))

Very late answer, but you can simply use:

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

Are you working with 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')

Yet another date parser library: Pendulum

This one's good, I promise.

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'

Rationale for this answer

A lot of pandas users stumble upon this question because they believe it is a python question more than a pandas one. This answer aims to be useful to folks who are already using these libraries and would be interested to know that there are ways to achieve these results within the scope of the library itself.

If you are not working with pandas or pendulum already, I definitely do not recommend installing them just for the sake of running this code! These libraries are heavy and come with a lot of plumbing under the hood. It is not worth the trouble when you can use the standard library instead.


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')

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to python-datetime

Getting today's date in YYYY-MM-DD in Python? Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes Convert DataFrame column type from string to datetime, dd/mm/yyyy format Python datetime strptime() and strftime(): how to preserve the timezone information How to convert a time string to seconds? Convert a python UTC datetime to a local datetime using only python standard library?