Skip to content

Commit 3675eee

Browse files
authored
[Edit] Python: time (#6043)
* Additional content * Errors :) * Update time.md minor fixes ---------
1 parent e307da7 commit 3675eee

File tree

1 file changed

+47
-4
lines changed
  • content/python/concepts/dates/terms/time

1 file changed

+47
-4
lines changed

content/python/concepts/dates/terms/time/time.md

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,24 +12,67 @@ CatalogContent:
1212
- 'paths/computer-science'
1313
---
1414

15-
The `datetime.time()` method returns a time in seconds that has passed since the epoch set on the computer.
15+
The **`datetime.time()`** method returns a time in seconds that has passed since the epoch set on the computer. The [`.sleep()`](https://www.codecademy.com/resources/docs/python/time-module/sleep) function suspends execution of the current thread for the specified number of seconds.
1616

1717
## Syntax
1818

1919
```pseudo
2020
datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
21+
time.sleep(seconds)
2122
```
2223

2324
The epoch is usually set as `January 1, 1970, 00:00:00 (UTC)` on most operating systems, excluding any leap seconds.
2425

26+
## Example
27+
28+
The following example demonstrates using `datetime.time()` to track when tea brewing starts and ends, with `.sleep()` creating a pause to simulate brewing time:
29+
30+
```py
31+
import datetime
32+
import time
33+
34+
# Create a simple timer for brewing tea
35+
def brew_tea():
36+
# Get start time
37+
start_time = datetime.datetime.now().time()
38+
print(f"Starting to brew tea at: {start_time.strftime('%H:%M:%S')}")
39+
40+
print("Brewing...")
41+
time.sleep(3) # Wait for 3 seconds
42+
43+
end_time = datetime.datetime.now().time()
44+
print(f"Tea is ready at: {end_time.strftime('%H:%M:%S')}")
45+
46+
brew_tea()
47+
```
48+
49+
The output of the above code will be:
50+
51+
```shell
52+
Starting to brew tea at: 21:54:54
53+
Brewing...
54+
Tea is ready at: 21:54:57
55+
```
56+
57+
> **Note:** Times shown will reflect system's current time.
58+
2559
## Codebyte Example
2660

27-
The time can be retrieved and stored in a variable as shown below:
61+
Run the following code to get a better understanding of how `.time()` and `.sleep()` works:
2862

2963
```codebyte/python
3064
import datetime
65+
import time
66+
67+
# Set meeting time
68+
meeting_time = datetime.datetime.now().time()
69+
print("Meeting time:", meeting_time)
3170
32-
meeting_time = datetime.time(10, 5, 31)
71+
# Simulate waiting for 2 seconds
72+
print("Waiting...")
73+
time.sleep(2)
3374
34-
print(meeting_time)
75+
# Print current time
76+
current_time = datetime.datetime.now().time()
77+
print("Current time:", current_time)
3578
```

0 commit comments

Comments
 (0)