class - datetime

最後更新: 2024-02-20

目錄

  • datetime.date Class
  • datetime.time Class
  • datetime.datetime Class
  • timedelta
  • strftime()
  • strptime()

 


查看 datetime 有什麼

 

import datetime

print(dir(datetime))

Attributes

  • datetime.date
  • datetime.time
  • datetime.datetime
  • datetime.timedelta
  • datetime.timezone
  • ....
     

datetime.date Class

 

from datetime import date

today = date.today()

# 2024-02-15
print today

# 不可以寫成 date(2024, 02, 15)
d = date(2024, 2, 15)
print(d)

Attributes

  • .year
  • .month
  • .day

Methods:

  • date.weekday()

 


datetime.time Class

 

from datetime import time

# 00:00:00
a = time()
print(a)

# 不可以寫成 time(16, 06, 10)
b = time(16, 6, 10)
# 16:06:10
print(b)

Attributes

  • .hour
  • .minute
  • .second
  • .microsecond

 


datetime.datetime Class

 

重要 function

  • now()
  • timestamp()
  • fromtimestamp()

now()

from datetime import datetime
curr_dt = datetime.now()

# 2024-02-15 15:58:29.708949

print(curr_dt)

a = datetime(2024, 2, 15)
b = datetime(2022, 2, 15, 16, 1)
c = datetime(2022, 2, 15, 16, 1, 6, 123456)

timestamp() & fromtimestamp()

timestamp = round(curr_dt.timestamp())
dt_object = datetime.fromtimestamp(timestamp)
print(dt_object)

Attributes

  • 有齊 date 及  time Class 的 Attributes

 


timedelta

 

計算 delta

from datetime import datetime

t1 = datetime(2024, 2, 15)

t2 = datetime(2024, 2, 13)

t3 = t1 - t2

# 2 days, 0:00:00

print(t3)

# <class 'datetime.timedelta'>

print(type(t3))

# 172800.0

print(t3.total_seconds())

# 172800

print(round(t3.total_seconds()))

Attributes(拎佢其中一 part)

  • days
  • seconds
  • microseconds

Only days, seconds and microseconds are stored internally. Arguments are converted to those units:

  • A millisecond is converted to 1000 microseconds.
  • A minute is converted to 60 seconds.
  • An hour is converted to 3600 seconds.
  • A week is converted to 7 days.

設定 delta

from datetime import timedelta

delta = timedelta(seconds=10)

t1 = datetime(2024, 2, 20)

# 2024-02-20 00:00:10

t1 = datetime(2024, 2, 20)

 


strftime()

 

.strftime("%H:%M:%S")

.strftime("%m/%d/%Y, %H:%M:%S")

i.e.

from datetime import datetime
curr_dt = datetime.now()

# '15:11:26'
curr_dt.strftime("%H:%M:%S")

format codes (C standard (1989 version))

  • %H       # 00, 01, …, 23
     
  • %M       # 00, 01, …, 59
     
  • %S       # 00, 01, …, 59
     
  • --------
  • %m       # 01, 02, …, 12
    %b        # Jan, Feb, ...
  • %d        # 01, 02, …, 31
  • %Y        # 2023, 2024 ...
     

 


strptime()

 

.strptime("str", "format")

 

Creative Commons license icon Creative Commons license icon