날짜를 일반 형식으로 인쇄하는 방법은 무엇입니까?
이것은 내 코드입니다.
import datetime
today = datetime.date.today()
print today
이것은 2008-11-22
정확히 내가 원하는 것입니다.
그러나, 나는 이것을 추가 할 목록을 가지고 있는데 갑자기 모든 것이 "놀라워"됩니다. 다음은 코드입니다.
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
그러면 다음이 인쇄됩니다.
[datetime.date(2008, 11, 22)]
어떻게 간단한 데이트를 할 수 2008-11-22
있습니까?
이유 : 날짜는 객체입니다.
Python에서 날짜는 객체입니다. 따라서이를 조작 할 때 타임 스탬프 나 그 어떤 것도 아닌 문자열이 아닌 객체를 조작하게됩니다.
Python의 모든 객체에는 두 가지 문자열 표현이 있습니다.
"인쇄"에 사용되는 정규 표현은
str()
함수를 사용하여 가져올 수 있습니다 . 대부분의 경우 사람이 읽을 수있는 가장 일반적인 형식이며 쉽게 표시하는 데 사용됩니다. 그래서str(datetime.datetime(2008, 11, 22, 19, 53, 42))
제공합니다'2008-11-22 19:53:42'
.객체 특성을 데이터로 표현하는 데 사용되는 대체 표현입니다.
repr()
함수를 사용하여 얻을 수 있으며 개발 또는 디버깅 중에 어떤 종류의 데이터를 조작하는지 알면 편리합니다.repr(datetime.datetime(2008, 11, 22, 19, 53, 42))
제공합니다'datetime.datetime(2008, 11, 22, 19, 53, 42)'
.
무슨 일이 있었는지 "인쇄"를 사용하여 날짜를 인쇄했을 때 str()
멋진 날짜 문자열을 볼 수 있도록 사용되었습니다 . 그러나를 인쇄 할 때 mylist
객체 목록을 인쇄했고 Python은를 사용하여 데이터 집합을 나타내려고했습니다 repr()
.
어떻게 : 그것으로 무엇을 하시겠습니까?
글쎄, 날짜를 조작 할 때는 항상 날짜 개체를 계속 사용하십시오. 그들은 수천 개의 유용한 메소드를 가지고 있으며 대부분의 Python API는 날짜가 객체가 될 것으로 예상합니다.
표시하려면을 사용하십시오 str()
. Python에서는 모든 것을 명시 적으로 캐스팅하는 것이 좋습니다. 따라서 인쇄 할 때가되면을 사용하여 날짜의 문자열 표현을 가져옵니다 str(date)
.
마지막 한가지. 날짜를 인쇄하려고 할 때 mylist
. 날짜를 인쇄하려면 컨테이너 (목록)가 아닌 날짜 개체를 인쇄해야합니다.
예를 들어 목록의 모든 날짜를 인쇄하려고합니다.
for date in mylist :
print str(date)
참고 특정 경우에 , 당신은 심지어 생략 할 수 있습니다 str()
인쇄는 당신을 위해 그것을 사용하기 때문이다. 하지만 습관이되어서는 안됩니다 :-)
코드를 사용한 실제 사례
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
고급 날짜 형식
날짜에는 기본 표시가 있지만 특정 형식으로 인쇄 할 수 있습니다. 이 경우 strftime()
메서드를 사용하여 사용자 지정 문자열 표현을 얻을 수 있습니다 .
strftime()
날짜 형식을 지정하는 방법을 설명하는 문자열 패턴이 필요합니다.
예 :
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
다음의 모든 문자 "%"
는 무언가에 대한 형식을 나타냅니다.
%d
일수%m
월 번호입니다%b
월 약어입니다.%y
연도 마지막 두 자리%Y
일년 내내
기타
공식 문서 를 보거나 McCutchen의 빠른 참조 를 모두 알 수는 없습니다.
PEP3101 이후 모든 객체는 모든 문자열의 메서드 형식에서 자동으로 사용되는 자체 형식을 가질 수 있습니다. datetime의 경우 형식은 strftime에서 사용되는 것과 동일합니다. 따라서 다음과 같이 위와 동일하게 할 수 있습니다.
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
이 형식의 장점은 동시에 다른 개체도 변환 할 수 있다는 것입니다. 형식화 된 문자열 리터럴 (Python 3.6, 2016-12-23 이후)
의 도입 으로 다음과 같이 작성할 수 있습니다.
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
현지화
날짜는 올바른 방식으로 사용하면 자동으로 현지 언어와 문화에 적응할 수 있지만 조금 복잡합니다. 어쩌면 SO (Stack Overflow) ;-)에 대한 또 다른 질문
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
편집하다:
Cees의 제안 이후, 저는 시간을 사용하기 시작했습니다.
import time
print time.strftime("%Y-%m-%d %H:%M")
date, datetime 및 time 객체는 모두 strftime (format) 메서드를 지원하여 명시 적 형식 문자열의 제어하에 시간을 나타내는 문자열을 만듭니다.
다음은 지시문 및 의미와 함께 형식 코드 목록입니다.
%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.
이것이 파이썬에서 datetime 및 time 모듈로 할 수있는 일입니다.
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")
다음과 같이 출력됩니다.
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
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')
This is shorter:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
# 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
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'
Simple answer -
datetime.date.today().isoformat()
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.
You can do:
mylist.append(str(today))
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
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.
Considering the fact you asked for something simple to do what you wanted, you could just:
import datetime
str(datetime.date.today())
For those wanting locale-based date and not including time, use:
>>> some_date.strftime('%x')
07/11/2019
You can use easy_date to make it easy:
import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')
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
.
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)
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 :)
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')]
참고URL : https://stackoverflow.com/questions/311627/how-to-print-a-date-in-a-regular-format
'developer tip' 카테고리의 다른 글
하나를 수정하지 않고 Python에서 두 목록을 연결하는 방법은 무엇입니까? (0) | 2020.10.02 |
---|---|
메타 데이터 파일 '.dll'을 찾을 수 없습니다. (0) | 2020.10.02 |
std :: string과 int를 연결하는 방법은 무엇입니까? (0) | 2020.10.02 |
Bash에서 stderr 및 stdout 리디렉션 (0) | 2020.10.02 |
"=="와 "is"사이에 차이가 있습니까? (0) | 2020.10.02 |