812

This is my code:

import datetime
today = datetime.date.today()
print(today)

This prints: 2008-11-22 which is exactly what I want.

But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)

This prints the following:

[datetime.date(2008, 11, 22)]

How can I get just a simple date like 2008-11-22?

Seanny123
  • 8,776
  • 13
  • 68
  • 124
NomadAlien
  • 9,090
  • 6
  • 25
  • 22

25 Answers25

1085

The WHY: dates are objects

In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.

Any object in Python has TWO string representations:

  • The regular representation that is used by print can be get using the str() function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you '2008-11-22 19:53:42'.

  • The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'.

What happened is that when you have printed the date using print, it used str() so you could see a nice date string. But when you have printed mylist, you have printed a list of objects and Python tried to represent the set of data, using repr().

The How: what do you want to do with that?

Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.

When you want to display them, just use str(). In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date).

One last thing. When you tried to print the dates, you printed mylist. If you want to print a date, you must print the date objects, not their container (the list).

E.G, you want to print all the date in a list :

for date in mylist :
    print str(date)

Note that in that specific case, you can even omit str() because print will use it for you. But it should not become a habit :-)

Practical case, using your code

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22

# It's better to always use str() because :

print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22

print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects

print "This is a new day : " + str(mylist[0]) 
>>> This is a new day : 2008-11-22

Advanced date formatting

Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime() method.

strftime() expects a string pattern explaining how you want to format your date.

E.G :

print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'

All the letter after a "%" represent a format for something:

  • %d is the day number (2 digits, prefixed with leading zero's if necessary)
  • %m is the month number (2 digits, prefixed with leading zero's if necessary)
  • %b is the month abbreviation (3 letters)
  • %B is the month name in full (letters)
  • %y is the year number abbreviated (last 2 digits)
  • %Y is the year number full (4 digits)

etc.

Have a look at the official documentation, or McCutchen's quick reference you can't know them all.

Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:

print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'

The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as

import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'

Localization

Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)

Stefan
  • 919
  • 2
  • 13
  • 24
Bite code
  • 578,959
  • 113
  • 301
  • 329
  • 3
    BTW Almost every data type in python is a class (except immutables, but they can be subclassed) http://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby – Yauhen Yakimovich Sep 11 '12 at 23:42
  • 1
    What do you mean "almost" ? str and int have a __class__ attribute, which contains 'type', therefor there are class themself, as they are instances of type metaclass. – Bite code Sep 12 '12 at 08:41
  • 4
    This is exactly the question of terminology: type != class?, i.e. is it enough to have type attribute (provide type inference mechanism to be qualified for an object) or should entity behave as an object. I am trying to resolve this for myself here http://programmers.stackexchange.com/questions/164570/formal-definition-for-term-pure-oo-language – Yauhen Yakimovich Sep 12 '12 at 10:44
  • 1
    If you are an instance of a class, you are an object. Why would you need it to be more complicated ? – Bite code Sep 12 '12 at 10:52
  • To understand how python implements OO paradigm. Of course the cool part about programming python - that you don't even have to know that date is an object or what OOP is - you can just write a piece of code and be happy about the fact that it works. I think asking question "what is an object?" leads to learning theory. I don't think there is a guarantee OOP will improve programming skill though - it is only a theoretical aspect that just eventually may. E.g. knowing that one can implement/achieve OO behavior without type inference (a=1;issubclass(type(a),int) is inferring a type) is cool. – Yauhen Yakimovich Sep 12 '12 at 11:10
  • 9
    Every value in Python is an object. Every object has a type. ["type" == "class"](http://stackoverflow.com/questions/4162578/python-terminology-class-vs-type) formally (also see `inspect.isclass` to make sure). People tend to say "type" for built-ins and "class" for the rest, but that's not important – Kos Mar 16 '13 at 13:11
  • I think the PEP3101 section should get moved closer to the top, and examples including strftime should be moved to the bottom in an appendix saying "If you're on an old version..." – ArtOfWarfare Feb 23 '16 at 15:50
  • Can you change your answer to python-3.x, please? – monkey Dec 13 '19 at 18:06
  • The author of this answer should consider a career in updating the core Python documentation, the quality of which is the ultimate cause of so many such questions ;) – Ed Randall May 23 '20 at 09:26
  • use in this case: telegram_message="""\" Critical_Open: """+f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S}"+"""
    Order """+thresholds[0]['name']+""" """+thresholds[0]['describe']+""" 
    more 10 s \""""
    – Nikolay Baranenko Jan 05 '21 at 12:22
  • I know I am like, 13 years late, but in Python 3, you have to use ```print``` with brackets. So, it should be ```print(anything you want to print)```. – theProCoder Jul 01 '21 at 00:53
414
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

Edit:

After Cees' suggestion, I have started using time as well:

import time
print time.strftime("%Y-%m-%d %H:%M")
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Daniel Magnusson
  • 9,541
  • 2
  • 38
  • 43
  • 2
    You can use from `datetime import datetime`, and then `print datetime().now().strftime("%Y-%m-%d %H:%M")`. Only a syntax difference. – Daniel Magnusson Nov 19 '13 at 08:44
  • 9
    `from datetime import date; date.today().strftime("%Y-%m-%d")` still looks unpythonic to me, but that's the best without `import time`. I think the datetime module is for date math. – Cees Timmerman Nov 19 '13 at 09:01
  • 2
    my favorite is `from datetime import datetime as dt` and now we can play with `dt.now()` – diewland Jun 24 '19 at 07:23
197

The date, datetime, and time objects all support a strftime(format) method, to create a string representing the time under the control of an explicit format string.

Here is a list of the format codes with their directive and meaning.

%a  Locale’s abbreviated weekday name.
%A  Locale’s full weekday name.      
%b  Locale’s abbreviated month name.     
%B  Locale’s full month name.
%c  Locale’s appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%f  Microsecond as a decimal number [0,999999], zero-padded on the left
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].      
%p  Locale’s equivalent of either AM or PM.
%S  Second as a decimal number [00,61].
%U  Week number of the year (Sunday as the first day of the week)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week)
%x  Locale’s appropriate date representation.    
%X  Locale’s appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  UTC offset in the form +HHMM or -HHMM.
%Z  Time zone name (empty string if the object is naive).    
%%  A literal '%' character.

This is what we can do with the datetime and time modules in Python

import time
import datetime

print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: ", datetime.datetime.now()
print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")

print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")

That will print out something like this:

Time in seconds since the epoch:    1349271346.46
Current date and time:              2012-10-03 15:35:46.461491
Or like this:                       12-10-03-15-35
Current year:                       2012
Month of year:                      October
Week number of the year:            40
Weekday of the week:                3
Day of year:                        277
Day of the month :                  03
Day of week:                        Wednesday
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Transformer
  • 3,642
  • 1
  • 22
  • 33
  • 1
    This solved my issue where the "more-upvoted-answers" didn't. But my issue was different than the OPs. I wanted months printed as text ("February" rather than "2") – Nathan majicvr.com Mar 12 '20 at 16:21
81

Use date.strftime. The formatting arguments are described in the documentation.

This one is what you wanted:

some_date.strftime('%Y-%m-%d')

This one takes Locale into account. (do this)

some_date.strftime('%c')
daviewales
  • 2,144
  • 21
  • 30
Ali Afshar
  • 40,967
  • 12
  • 95
  • 109
46

This is shorter:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
30
# convert date time to regular format.

d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)

# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)

OUTPUT

2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34
Waqas Ali
  • 1,441
  • 2
  • 20
  • 25
27

Or even

from datetime import datetime, date

"{:%d.%m.%Y}".format(datetime.now())

Out: '25.12.2013

or

"{} - {:%d.%m.%Y}".format("Today", datetime.now())

Out: 'Today - 25.12.2013'

"{:%A}".format(date.today())

Out: 'Wednesday'

'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())

Out: '__main____2014.06.09__16-56.log'

b1_
  • 2,069
  • 1
  • 27
  • 39
19

Simple answer -

datetime.date.today().isoformat()
Flame of udun
  • 2,136
  • 7
  • 35
  • 79
9

With type-specific datetime string formatting (see nk9's answer using str.format().) in a Formatted string literal (since Python 3.6, 2016-12-23):

>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'

The date/time format directives are not documented as part of the Format String Syntax but rather in date, datetime, and time's strftime() documentation. The are based on the 1989 C Standard, but include some ISO 8601 directives since Python 3.6.

handle
  • 5,859
  • 3
  • 54
  • 82
  • 1
    Note that I've also added this information to the accepted [answer](https://stackoverflow.com/a/311655/1619432). – handle Nov 17 '17 at 09:59
  • strftime doesn't really include an "ISO 8601 output". There are "directives", but only for specific tokens like "day of week", not a whole ISO 8601 timestamp, which I've always found annoying. – anarcat Nov 30 '18 at 16:37
  • ```f"{datetime.datetime.now().astimezone():%Y-%m-%dT%H:%M:%S.%f}"[:-3]+f"{datetime.datetime.now().astimezone():%z}"``` to include milliseconds and timezone as well – Gordon McDonald Jun 28 '22 at 07:23
7

I hate the idea of importing too many modules for convenience. I would rather work with available module which in this case is datetime rather than calling a new module time.

>>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
>>> a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'
anon
  • 1,258
  • 10
  • 17
rickydj
  • 629
  • 5
  • 17
  • 1
    I think it'd be more efficient to do that in one line of code by doing `a = datetime.datetime(2015, 04, 01, 23, 22).strftime('%Y-%m-%d %H:%M)` – Dorian Dore May 15 '15 at 03:11
6

You need to convert the datetime object to a str.

The following code worked for me:

import datetime

collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
    
print(collection)

Let me know if you need any more help.

Nerveless_child
  • 1,366
  • 2
  • 15
  • 19
Simon Johnson
  • 7,802
  • 5
  • 37
  • 49
  • 4
    Come on ! Don't encourage a newbie to store a string instead of a date object. He won't be able to know when it's a good or a bad idea... – Bite code Nov 22 '08 at 19:17
  • e-satis: If all you need is a string, what's the big deal? We store our firmware build dates as strings all the time -- sometimes storing a whole object is overkill when all you need is a simple timestamp (YAGNI and all). – HanClinto Nov 22 '08 at 19:58
  • 3
    Yes, in certains case it is. I just mean just a newbie won't be able to identify these cases. So let's start with the right foot :-) – Bite code Nov 23 '08 at 18:25
4

In Python you can format a datetime using the strftime() method from the date, time and datetime classes in the datetime module.

In your specific case, you are using the date class from datetime. You can use the following snippet to format the today variable into a string with the format yyyy-MM-dd:

import datetime

today = datetime.date.today()
print("formatted datetime: %s" % today.strftime("%Y-%m-%d"))

In the following a more complete example:

import datetime
today = datetime.date.today()

# datetime in d/m/Y H:M:S format
date_time = today.strftime("%d/%m/%Y, %H:%M:%S")
print("datetime: %s" % date_time)

# datetime in Y-m-d H:M:S format
date_time = today.strftime("%Y-%m-%d, %H:%M:%S")
print("datetime: %s" % date_time)

# format date
date = today.strftime("%d/%m/%Y")
print("date: %s" % time)

# format time
time = today.strftime("%H:%M:%S")
print("time: %s" % time)

# day
day = today.strftime("%d")
print("day: %s" % day)

# month
month = today.strftime("%m")
print("month: %s" % month)

# year
year = today.strftime("%Y")
print("year: %s" % year)

More directives:

Python strftime directives from 1989 C standards

Sources:

3

You can do:

mylist.append(str(today))
Igal Serban
  • 10,558
  • 3
  • 35
  • 40
3

Considering the fact you asked for something simple to do what you wanted, you could just:

import datetime
str(datetime.date.today())
Ward Taya
  • 63
  • 2
3

For those wanting locale-based date and not including time, use:

>>> some_date.strftime('%x')
07/11/2019
Liran H
  • 9,143
  • 7
  • 39
  • 52
3

For pandas.Timestamps, strftime() can be used e.g.:

utc_now = datetime.now()

For isoformat:

utc_now.isoformat()

For any format e.g.:

utc_now.strftime("%m/%d/%Y, %H:%M:%S")
ntg
  • 12,950
  • 7
  • 74
  • 95
2

Since the print today returns what you want this means that the today object's __str__ function returns the string you are looking for.

So you can do mylist.append(today.__str__()) as well.

izstas
  • 5,004
  • 3
  • 42
  • 56
2

You may want to append it as a string?

import datetime

mylist = []
today = str(datetime.date.today())
mylist.append(today)

print(mylist)
Nerveless_child
  • 1,366
  • 2
  • 15
  • 19
HanClinto
  • 9,423
  • 3
  • 30
  • 31
2
from datetime import date

def today_in_str_format():
    return str(date.today())

print (today_in_str_format())

This will print 2018-06-23 if that's what you want :)

Nerveless_child
  • 1,366
  • 2
  • 15
  • 19
Erix
  • 31
  • 5
1

A quick disclaimer for my answer - I've only been learning Python for about 2 weeks, so I am by no means an expert; therefore, my explanation may not be the best and I may use incorrect terminology. Anyway, here it goes.

I noticed in your code that when you declared your variable today = datetime.date.today() you chose to name your variable with the name of a built-in function.

When your next line of code mylist.append(today) appended your list, it appended the entire string datetime.date.today(), which you had previously set as the value of your today variable, rather than just appending today().

A simple solution, albeit maybe not one most coders would use when working with the datetime module, is to change the name of your variable.

Here's what I tried:

import datetime
mylist = []
present = datetime.date.today()
mylist.append(present)
print present

and it prints yyyy-mm-dd.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Mark S.
  • 29
  • 5
1

You can use easy_date to make it easy:

import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37
1

Here is how to display the date as (year/month/day) :

from datetime import datetime
now = datetime.now()

print '%s/%s/%s' % (now.year, now.month, now.day)
zondo
  • 19,901
  • 8
  • 44
  • 83
0

I don't fully understand but, can use pandas for getting times in right format:

>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>> 

And:

>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']

But it's storing strings but easy to convert:

>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

maybe the shortest solution, which exactly matches your situation, would be:

mylist.append(str(AnyDate)[:10])

or even shorter, e.g.:

f'{AnyDate}'[:10]

PS: it doesn't need to be today.

NegaOverflow
  • 138
  • 1
  • 11
-1
import datetime
import time

months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
datetimeWrite = (time.strftime("%d-%m-%Y "))
date = time.strftime("%d")
month= time.strftime("%m")
choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
result = choices.get(month, 'default')
year = time.strftime("%Y")
Date = date+"-"+result+"-"+year
print Date

In this way you can get Date formatted like this example: 22-Jun-2017

tanmayee
  • 15
  • 1
  • 3
    Too much code for something you could get in one line. With `%b` you will get the first three month words, and with `%B` the entire month. Example: `datetime.datetime.now().strftime("%Y-%b-%d %H:%M:%S")` will return '2018-Oct-04 09:44:08' – Víctor López Oct 04 '18 at 07:44