How to print a date in a regular format?

2018-12-31 04:40发布

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 on earth can I get just a simple date like "2008-11-22"?

21条回答
浮光初槿花落
2楼-- · 2018-12-31 05:20

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')
查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 05:21

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.

查看更多
不再属于我。
4楼-- · 2018-12-31 05:24
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")
查看更多
裙下三千臣
5楼-- · 2018-12-31 05:25

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)
查看更多
唯独是你
6楼-- · 2018-12-31 05:27

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.

查看更多
零度萤火
7楼-- · 2018-12-31 05:30
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 :)

查看更多
登录 后发表回答