상세 컨텐츠

본문 제목

datetime

Python

by techbard 2024. 12. 23. 11:08

본문

반응형
# convert a given number of seconds into hours, minutes, 
# and seconds
total_seconds = 7385
hours, remaining_seconds = divmod(total_seconds, 3600)
minutes, second = divmod(remaining_seconds, 60)

print(f"{total_seconds=}", end=' ')
print(f"{hours=}", end=' ')
print(f"{minutes=}", end=' ')
print(f"{second=}")

# 결과
total_seconds=7385 hours=2 minutes=3 second=5

 

from datetime import date
from datetime import time
from datetime import datetime

def main():
    # date
    today = date.today()
    print(f"Today's date is {today}")
    print(f"Date componetns: {today.year}, {today.month}, {today.day}")
    print(f"Today's weekday # is {today.weekday()}")
    days = ["mon", "tue", "wed", "thur", "fri", "sat", "sun"]
    print(f"Which is a {days[today.weekday()]}")

    # time
    now = datetime.now()
    print(f"The current data and time is {now}")

    time = datetime.time(datetime.now())
    print(f"The current time is {time}")

if __name__ == '__main__':
    main()

# Output:
Today's date is 2024-12-23
Date componetns: 2024, 12, 23
Today's weekday # is 0
Which is a mon
The current data and time is 2024-12-23 10:31:17.613002
The current time is 10:31:17.613022

 

# Using timedelta objects
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

print(timedelta(days=365, hours=5, minutes=1))
now = datetime.now()
print(f"Today is {now}")

print(f"1 year from now it will be {str(now + timedelta(days=365))}")
print(f"In 2 weeks and 3 days it will be {str(now + timedelta(weeks=2, days=3))}")
t = datetime.now() - timedelta(weeks=1)
s = t.strftime("%A %B %d, %Y")
print(f"1 week ago it was {s}")

# Output:
365 days, 5:01:00
Today is 2024-12-23 11:06:59.283354
1 year from now it will be 2025-12-23 11:06:59.283354
In 2 weeks and 3 days it will be 2025-01-09 11:06:59.283354
1 week ago it was Monday December 16, 2024
반응형

관련글 더보기

댓글 영역