Skip to content

Commit

Permalink
[Edit] Python: time (#6043)
Browse files Browse the repository at this point in the history
* Additional content

* Errors :)

* Update time.md

minor fixes

---------
  • Loading branch information
avdhoottt authored Jan 29, 2025
1 parent e307da7 commit 3675eee
Showing 1 changed file with 47 additions and 4 deletions.
51 changes: 47 additions & 4 deletions content/python/concepts/dates/terms/time/time.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,67 @@ CatalogContent:
- 'paths/computer-science'
---

The `datetime.time()` method returns a time in seconds that has passed since the epoch set on the computer.
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.

## Syntax

```pseudo
datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
time.sleep(seconds)
```

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

## Example

The following example demonstrates using `datetime.time()` to track when tea brewing starts and ends, with `.sleep()` creating a pause to simulate brewing time:

```py
import datetime
import time

# Create a simple timer for brewing tea
def brew_tea():
# Get start time
start_time = datetime.datetime.now().time()
print(f"Starting to brew tea at: {start_time.strftime('%H:%M:%S')}")

print("Brewing...")
time.sleep(3) # Wait for 3 seconds

end_time = datetime.datetime.now().time()
print(f"Tea is ready at: {end_time.strftime('%H:%M:%S')}")

brew_tea()
```

The output of the above code will be:

```shell
Starting to brew tea at: 21:54:54
Brewing...
Tea is ready at: 21:54:57
```

> **Note:** Times shown will reflect system's current time.
## Codebyte Example

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

```codebyte/python
import datetime
import time
# Set meeting time
meeting_time = datetime.datetime.now().time()
print("Meeting time:", meeting_time)
meeting_time = datetime.time(10, 5, 31)
# Simulate waiting for 2 seconds
print("Waiting...")
time.sleep(2)
print(meeting_time)
# Print current time
current_time = datetime.datetime.now().time()
print("Current time:", current_time)
```

0 comments on commit 3675eee

Please sign in to comment.