๐ŸŒ™ Python datetime ๋ชจ๋“ˆ: ํ˜„์žฌ ๋‚ ์งœ์™€ ์‹œ๊ฐ„, ๋ฌธ์ž์—ด ํฌ๋งท

Diorยท2022๋…„ 11์›” 6์ผ
0

[Today I Learned]

๋ชฉ๋ก ๋ณด๊ธฐ
2/3
post-thumbnail

ํ”„๋กœ์ ํŠธ ์ง„ํ–‰ ์ค‘์— ๋™์ผํ•œ ์ƒํ™ฉ์—์„œ
๋ˆ„๊ตฌ๋Š” datetime.today()๋ฅผ ๋ˆ„๊ตฌ๋Š” datetime.now()๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

๋‘˜์˜ ์ฐจ์ด์ ์ด ๊ถ๊ธˆํ•ด์กŒ๋‹ค.
์ถ”๊ฐ€์ ์œผ๋กœ ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” date ํด๋ž˜์Šค, strftime() ๋ฉ”์„œ๋“œ๋ฅผ ํ•จ๊ป˜ ์ •๋ฆฌํ•œ๋‹ค.


๐Ÿ“… datetime ๋ชจ๋“ˆ

๋‚ ์งœ์™€ ์‹œ๊ฐ„์„ ์กฐ์ž‘ํ•˜๋Š” Class๋ฅผ ์ œ๊ณตํ•œ๋‹ค.

calss datetime.date

    Attribute: year, month, day

class datetime.datetime

    Attribute: year, month, day, hour, minute, second, microsecond, tzinfo

etc.


โœ” date ๊ฐ์ฒด

from datetime import date

special_day = date(1998, 10, 4)
print(special_day)
> 1998-10-04

today = date.today()
print(today)
> 2022-11-07

print(today.year)
> 2022

print(today.month)
> 11

print(today.day)
> 7

โœ” datetime ๊ฐ์ฒด

from datetime import datetime

special_day = datetime(1998, 10, 7)
print(today)
> 1998-10-04 00:00:00

print(datetime.now())
> 2022-11-07 01:00:42.090442

print(datetime.today())
> 2022-11-07 01:00:42.091441

print(today.yaer)
print(today.month)
print(today.day)
> ์ƒ๋žต

datetime.now(tz=None)
์„ ํƒ์  ์ธ์ž tz๊ฐ€ None์ด๊ฑฐ๋‚˜ ์ง€์ •๋˜์ง€ ์•Š์œผ๋ฉด, today()์™€ ์œ ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
tz๊ฐ€ None์ด ์•„๋‹ˆ๋ฉด, tzinfo ์„œ๋ธŒ ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค์—ฌ์•ผ ํ•˜๋ฉฐ, ํ˜„์žฌ ๋‚ ์งœ์™€ ์‹œ๊ฐ„์ด tz์˜ ์‹œ๊ฐ„๋Œ€๋กœ ๋ณ€ํ™˜๋ฉ๋‹ˆ๋‹ค.

์ด ํ•จ์ˆ˜๋Š” today()์™€ utcnow()๋ณด๋‹ค ์„ ํ˜ธ๋ฉ๋‹ˆ๋‹ค.


โœ” strftime(format) ๋ฉ”์„œ๋“œ

format ํ˜•์‹์€ ์•„๋ž˜ ๊ณต์‹๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ .

from datetime import date, datetime

date_today = date.today()           # date ๊ฐ์ฒด
datetime_today = datetime.now()     # datetime ๊ฐ์ฒด


print(date_today.strftime('%Y-%m-%d'))
> 2022-11-07

print(datetime_today.strftime('%Y-%m-%d: %H:%M:%S'))
> 2022-11-07: 01:19:59

๐Ÿ™„ P.S.

๊ฒฐ๋ก ์€ datetime.now(), datetime.today() ๋ฌด์—‡์„ ์‚ฌ์šฉํ•ด๋„ ์ƒ๊ด€ ์—†์—ˆ๋‹ค.
now(tz=None)๋Š” tz์ด ์ถ”๊ฐ€๋œ ๊ฒƒ์ด๋‹ค.
๋” ์„ ํ˜ธ๋˜๋Š” now()๋ฅผ ์“ฐ๋ฉด ๋  ๊ฒƒ ๊ฐ™๋‹ค.

[์ฐธ๊ณ ์ž๋ฃŒ]
https://docs.python.org/ko/3/library/datetime.html#module-datetime

๐Ÿ™‡๐Ÿปโ€ ์ž˜๋ชป๋œ ์ •๋ณด๋Š” ๋Œ“๊ธ€์„ ํ†ตํ•ด ์•Œ๋ ค์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

profile
Focus on growth rather than material

0๊ฐœ์˜ ๋Œ“๊ธ€