908

Is there a nicer way than the following to return today's date in the YYYY-MM-DD format?

str(datetime.datetime.today()).split()[0]
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Pyderman
  • 14,809
  • 13
  • 61
  • 106
  • 5
    maybe this? \n now = datetime.datetime.now() \n str(now.strftime("Y-%m-%d") – Gombat Sep 09 '15 at 23:24
  • 7
    @Gombat What I mean is in my experience, there's usually a built in way of getting the thing we want in Python without having to split, index, concat, join etc. – Pyderman Sep 09 '15 at 23:41
  • 2
    [pandas and pendulum alternatives are available for those working with these libraries.](https://stackoverflow.com/a/55371556/4909087) – cs95 Apr 01 '19 at 05:18

12 Answers12

1516

Use strftime:

>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'

To also include a zero-padded Hour:Minute:Second at the end:

>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'

To get the UTC date and time:

>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
diegueus9
  • 29,351
  • 16
  • 62
  • 74
  • 1
    there is also a strong probability that "%x" would work ... but that is locale dependent – Joran Beasley Sep 09 '15 at 23:36
  • 13
    how about just `time.strftime("%Y-%m-%d")`? – aderchox Aug 27 '19 at 04:00
  • 10
    For UTC date: `datetime.utcnow().strftime('%Y-%m-%d')` – Agost Biro Dec 08 '19 at 11:13
  • 1
    Worth noting that `date` has this available as well as `datetime` – dummyDev Apr 24 '20 at 20:46
  • 3
    Here's a helpful list to get variations of OPs desired result: https://strftime.org/ – Henrik Jun 03 '20 at 06:41
  • Upvoted. Here's my favorite format: `datetime.today().strftime("%Y%m%d-%H%M%S.%f")`. Example output: `'20230803-195136.416752'`. The meaning is `YYYYMMDD-HHMMSS.microseconds`. That's "Year Month Day - Hours Minutes Seconds.microseconds". I use this commonly for auto-sorting log files and temporary files. – Gabriel Staples Aug 04 '23 at 02:52
235

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'
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
kmonsoor
  • 7,600
  • 7
  • 41
  • 55
  • 2
    Is it possible to change the separator to `/`? – Stevoisiak Jan 31 '18 at 19:07
  • 9
    @StevenVascellaro it would be `date.today().strftime('%Y/%m/%d')` – kmonsoor Jan 31 '18 at 20:38
  • 4
    @StevenVascellaro Bad idea. The reader normally assumes the separator `.` to 'D.M.Y', the separator `/` to `M/D/Y` and the separator `-` to `Y-M-D`. Although not everybody follows these guidelines, it would help reading dates internationally as long as not everybody has switched to `Y-M-D`. – glglgl Feb 15 '18 at 10:02
  • 1
    @glglgl I’m working with an api that assumes the American date format m/d/y. I’ve already changed the order in my application. – Stevoisiak Feb 15 '18 at 12:50
  • @StevenVascellaro But then you'd need `M/D/Y`, wouldn't you? – glglgl Feb 15 '18 at 12:51
  • 1
    @glglgl Yes, I am using m/d/y – Stevoisiak Feb 15 '18 at 12:55
  • This is the best answer because more explicit `.date` is used instead of `.datetime` which requires stripping out the time. – WinEunuuchs2Unix Jul 31 '21 at 22:12
  • A short answer: `datetime.date.today().isoformat()` --but even shorter: `str(datetime.date.today())` – MarkHu Apr 20 '22 at 18:13
  • String value of date in str( datetime.date.today() ) is different than that in str( ( datetime.date.today() ) ). -- another place where the legacy behaviour of repr and str is non-intuitive. – david Mar 17 '23 at 02:58
91

I always use the isoformat() method 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 the standard ISO 8601 format as well.

from datetime import datetime
now = datetime.today().isoformat()
print(now)  # '2018-12-05T11:15:55.126382'
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
JdH
  • 936
  • 6
  • 5
84

Very late answer, but you can simply use:

import time
today = time.strftime("%Y-%m-%d")
# 2023-08-30
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
52

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.

Bill Bell
  • 21,021
  • 5
  • 43
  • 58
  • 33
    for a simple task like this, why use another library when built-in library can do it as simply. Of course, if user need other multitude of {time, date}-related functions, bringing in a new library makes sense. – kmonsoor Aug 16 '18 at 14:09
  • 5
    you made me laugh on reading that 2nd line of code. how's that better than `print(date.today())` >> "2018-12-16"?? lol and easily get the int values `t.year,t.month,t.day+1` >> (2018, 12, 17) where `t = date.today()` and the fact people don't have to call green arrow to tell them the time. oh god this is too much code to remember... – Puddle Dec 16 '18 at 16:46
  • 2
    @Puddle: Hilarious. – Bill Bell Dec 16 '18 at 20:49
  • @kmonsoor How is `import datetime` different than `import arrow`? Sure one is built in, but if `arrow` provides a more convenient format, then why not use it? – information_interchange Nov 19 '19 at 03:04
  • 1
    @information_interchange you already answered your question. Built-in vs not. If someone needs those extra stuff, sure, why not `arrow`? But, for many simple projects, it's just unnecessary. Also, in many company-internal projects, ppl need to get approval for including new libraries. – kmonsoor Nov 19 '19 at 11:28
35

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 4
    Great news pandas has it too! – ZygD Apr 18 '19 at 10:41
  • 1
    This one is really awesome, specifically when one's working on pandas – loveR Oct 24 '19 at 12:15
  • pd.to_datetime(day).date() is useful if you're using pandas and don't want to convert to a str. Thanks! – Brndn Apr 16 '20 at 14:26
  • @cs95 The main question is "How to get YYYY-MM-DD format". Not "how to get the current date". Your answer is irrelevant. You can try to extend it by stripping everything after "YYYY-MM-DD" to answer the question. – Nairum Jul 13 '20 at 13:51
  • For "pendulum" use: `now = pendulum.now()`, `now = now.format('YYYY-MM-DD')` – Nairum Jul 13 '20 at 14:00
  • @AlexeiMarinichenko I disagree with the premise, there are actually two questions here. I've focused on the first one, because the answer to the second one is less interesting (strftime). Besides, this answer is useful for those who want the date object and not the date string. – cs95 Jan 18 '21 at 09:27
12
from datetime import datetime

date = datetime.today().date()

print(date)
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Don Dominic
  • 121
  • 1
  • 2
  • 4
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Suraj Rao Jan 29 '21 at 17:11
  • This is a longer/worse variant. Prefer the shorter `str(datetime.date.today())` – MarkHu Apr 20 '22 at 18:17
9

If you need e.g. pacific standard time (PST) you can do

from datetime import datetime
import pytz

tz = pytz.timezone('US/Pacific')
datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')
# '2021-09-02 10:21:41'
Nic Scozzaro
  • 6,651
  • 3
  • 42
  • 46
9

Use f-strings, they are usually the best choice for any text-variable mix:

from datetime import date
print(f'{date.today():%Y-%m-%d}')

Taken from Python f-string formatting not working with strftime inline which has the official links as well.

questionto42
  • 7,175
  • 4
  • 57
  • 90
2

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()))
Sway Wu
  • 379
  • 3
  • 8
1

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)
Darwin
  • 1,695
  • 1
  • 19
  • 29
  • Try not to use python built in functions and variables as local variables (ex: today, year, day). Also, the request from the user is to get today's date in YYYY-MM-DD format. Can you try and answer to the question (format YYYY-MM-DD). – Joe Ferndz Aug 29 '20 at 00:35
-3

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)
shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34