본문 바로가기
개념/혼자 공부하는 파이썬

python) datetime package

by kiseno 2024. 11. 5.
728x90
반응형
SMALL
import datetime

now = datetime.datetime.now()

print(now.year, now.month, now.day, now.hour, now.minute, now.second);

This code snippet is a straightforward example of how to use the `datetime` module in Python to get the current date and time, and then print specific components of it such as the year, month, day, hour, minute, and second. Let's break it down:

1. **`import datetime`**: This line imports the `datetime` module, which provides classes for manipulating dates and times.

2. **`now = datetime.datetime.now()`**: Here, `datetime.datetime.now()` is called to get a `datetime` object representing the current local date and time. This object is stored in the variable `now`.

3. **`print(now.year, now.month, now.day, now.hour, now.minute, now.second);`**: This line prints the year, month, day, hour, minute, and second components of the `now` object, separated by spaces. Each component is accessed as an attribute of the `now` object. The semicolon at the end is optional in Python and does not affect the execution.

When this code is executed, it will output the current year, month, day, hour, minute, and second according to the system's local time. For example, if the current date and time were March 31, 2024, 15:30:45, the output would be:
```
2024 3 31 15 30 45
```

This is a useful technique for logging, time-stamping, or any functionality that requires knowledge of the current date and time.

728x90
반응형
LIST