[python] How to print a date in a regular format?

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?

This question is related to python datetime date

The answer is


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'


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.


You can use easy_date to make it easy:

import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')

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


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

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'


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.


This is shorter:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'

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

>>> some_date.strftime('%x')
07/11/2019

Simple answer -

datetime.date.today().isoformat()

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

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.


You need to convert the date time object to a string.

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.


# 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

Simple answer -

datetime.date.today().isoformat()

You can do:

mylist.append(str(today))

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

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.


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

You need to convert the date time object to a string.

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.


from datetime import date
def time-format():
  return str(date.today())
print (time-format())

this will print 6-23-2018 if that's what you want :)


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

import datetime
str(datetime.date.today())

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

# 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

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

You need to convert the date time object to a string.

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.


You may want to append it as a string?

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

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

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'

You may want to append it as a string?

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

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)

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

import datetime
str(datetime.date.today())

You can do:

mylist.append(str(today))

You may want to append it as a string?

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

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

>>> some_date.strftime('%x')
07/11/2019

You can do:

mylist.append(str(today))

This is shorter:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'

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

from datetime import date
def time-format():
  return str(date.today())
print (time-format())

this will print 6-23-2018 if that's what you want :)


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'

You need to convert the date time object to a string.

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.


You can do:

mylist.append(str(today))

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)

You may want to append it as a string?

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

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

You can use easy_date to make it easy:

import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')

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.


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

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


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 date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?