Skip to content
Merged
Changes from 23 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
d0dd9bd
[Edit] SQL: DATEDIFF()
mamtawardhani May 21, 2025
9f5c19b
Update datediff.md
mamtawardhani May 21, 2025
c32e9f3
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
4170ba2
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
8325585
Merge branch 'Codecademy:main' into main
mamtawardhani May 26, 2025
8f6f8e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 27, 2025
e4c54e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 28, 2025
7b3b9c0
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
27ecefd
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
0392da4
Merge branch 'Codecademy:main' into main
mamtawardhani May 30, 2025
d550fa7
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 2, 2025
793be7d
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
2f03b61
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
25eb0ab
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
73e0e3b
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 4, 2025
44f4c63
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 5, 2025
545a8da
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 6, 2025
7975776
[Edit]Python: datetime.now()
mamtawardhani Jun 8, 2025
f9573fb
Update now.md
mamtawardhani Jun 8, 2025
9d357fa
Update content/python/concepts/dates/terms/now/now.md
avdhoottt Jun 19, 2025
bf5db9e
Update content/python/concepts/dates/terms/now/now.md
avdhoottt Jun 19, 2025
333daa5
Update content/python/concepts/dates/terms/now/now.md
avdhoottt Jun 19, 2025
c08a404
Merge branch 'main' into datetime-now
avdhoottt Jun 19, 2025
b901f9a
Format
avdhoottt Jun 19, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 173 additions & 11 deletions content/python/concepts/dates/terms/now/now.md
Original file line number Diff line number Diff line change
@@ -1,37 +1,199 @@
---
Title: '.datetime.now()'
Description: 'Returns the current date and timestamp.'
Title: 'datetime.now()'
Description: 'Returns a datetime object representing the current local date and time.'
Subjects:
- 'Computer Science'
- 'Data Science'
Tags:
- 'Date'
- 'Functions'
- 'Methods'
- 'Time'
CatalogContent:
- 'learn-python-3'
- 'paths/computer-science'
---

The `.datetime.now()` method returns a new `datetime` object with the current local date and timestamp.
The **`datetime.now()`** method is a class method from Python's [`datetime`](https://www.codecademy.com/resources/docs/python/dates) module that returns a `datetime` object representing the current local date and time. This method captures the exact moment when it is called, including the year, month, day, hour, minute, second, and microsecond components. It serves as the primary way to obtain real-time temporal information within Python applications.

The `datetime.now()` method is commonly used in applications that require timestamping, logging activities, scheduling tasks, measuring execution time, and creating time-based records. It is essential for web applications that need to track user activity, financial systems that require transaction timestamps, monitoring systems that log events, and any application where recording the current moment is crucial for functionality or compliance.

## Syntax

```pseudo
datetime.datetime.now(time_zone=None)
datetime.now(tz=None)
```

**Parameters:**

- `tz` (Optional): Timezone parameter that specifies the timezone for which the current date and time should be returned. If `None` (default), returns the current local date and time. Accepts a timezone object that implements the `tzinfo` abstract base class.

**Return value:**

A `datetime` object representing the current date and time. The returned object contains attributes for year, month, day, hour, minute, second, and microsecond.

## Example 1: Getting Current Date and Time

This example demonstrates the basic usage of `datetime.now()` to retrieve the current date and time:

```py
# Import the datetime class from datetime module
from datetime import datetime

# Get the current date and time
current_datetime = datetime.now()

# Display the complete datetime object
print("Current date and time:", current_datetime)

# Access individual components
print("Year:", current_datetime.year)
print("Month:", current_datetime.month)
print("Day:", current_datetime.day)
print("Hour:", current_datetime.hour)
print("Minute:", current_datetime.minute)
print("Second:", current_datetime.second)
```

The output of the code is:

```shell
Current date and time: 2025-06-08 14:30:45.123456
Year: 2025
Month: 6
Day: 8
Hour: 14
Minute: 30
Second: 45
```

>**Note:** The actual output will change every time the code is run, because `datetime.now()` captures the exact current date and time at the moment of execution.

This example shows how to import the `datetime` class and use the `now()` method to get the current timestamp. The output displays both the complete `datetime` object and its individual components, making it easy to extract specific time elements when needed.

## Example 2: Event Logging System

This example demonstrates using `datetime.now()` to create an event logging system that timestamps important application events:

```py
from datetime import datetime

class EventLogger:
def __init__(self):
self.events = []

def log_event(self, event_type, description):
# Capture the exact moment when event occurs
timestamp = datetime.now()

# Create event record with timestamp
event_record = {
'timestamp': timestamp,
'type': event_type,
'description': description,
'formatted_time': timestamp.strftime("%Y-%m-%d %H:%M:%S")
}

# Store the event
self.events.append(event_record)
print(f"[{event_record['formatted_time']}] {event_type}: {description}")

def get_events_summary(self):
print(f"\nTotal events logged: {len(self.events)}")
for event in self.events:
print(f"- {event['formatted_time']}: {event['type']}")

# Create logger and log various events
logger = EventLogger()
logger.log_event("USER_LOGIN", "User johndoe logged into the system")
logger.log_event("FILE_UPLOAD", "Document report.pdf uploaded successfully")
logger.log_event("ERROR", "Database connection timeout occurred")

# Display summary
logger.get_events_summary()
```

The result from the `.datetime.now()` method contains the year, month, day, hour, minute, second, and microsecond (expressed as `YYYY-MM-DD hh:mm:ss.ffffff`).
The output of this code will be:

```shell
[2025-06-08 14:30:45] USER_LOGIN: User johndoe logged into the system
[2025-06-08 14:30:46] FILE_UPLOAD: Document report.pdf uploaded successfully
[2025-06-08 14:30:47] ERROR: Database connection timeout occurred

Total events logged: 3
- 2025-06-08 14:30:45: USER_LOGIN
- 2025-06-08 14:30:46: FILE_UPLOAD
- 2025-06-08 14:30:47: ERROR
```

It also accepts an optional `time_zone` parameter, which is set to `None` by default.
This example shows a practical application where `datetime.now()` is used to timestamp events in a logging system. Each event is recorded with the precise moment it occurred, which is essential for debugging, auditing, and monitoring system activity.

## Codebyte Example
## Codebyte Example: Task Scheduler with Deadlines

The current date and time can be retrieved and stored in a variable as shown below:
This example demonstrates using `datetime.now()` in a task management system to track deadlines and calculate remaining time:

```codebyte/python
import datetime
from datetime import datetime, timedelta

class TaskScheduler:
def __init__(self):
self.tasks = []

def add_task(self, name, hours_until_deadline):
# Get current time and calculate deadline
created_at = datetime.now()
deadline = created_at + timedelta(hours=hours_until_deadline)

task = {
'name': name,
'created_at': created_at,
'deadline': deadline,
'status': 'pending'
}

self.tasks.append(task)
print(f"Task '{name}' created at {created_at.strftime('%H:%M:%S')}")
print(f"Deadline: {deadline.strftime('%Y-%m-%d %H:%M:%S')}")

def check_task_status(self):
current_time = datetime.now()
print(f"\nTask status check at {current_time.strftime('%H:%M:%S')}:")

today = datetime.datetime.now()
for task in self.tasks:
time_remaining = task['deadline'] - current_time

print(today)
if time_remaining.total_seconds() > 0:
hours_left = time_remaining.total_seconds() / 3600
print(f"- {task['name']}: {hours_left:.1f} hours remaining")
else:
print(f"- {task['name']}: OVERDUE by {abs(time_remaining)}")

# Create scheduler and add tasks
scheduler = TaskScheduler()
scheduler.add_task("Complete project report", 8)
scheduler.add_task("Review code changes", 2)
scheduler.add_task("Send client email", 24)

# Check status
scheduler.check_task_status()
```

This example demonstrates a task scheduler that uses `datetime.now()` to track when tasks are created and calculate remaining time until deadlines. This is useful for project management applications, reminder systems, and time-sensitive workflow management.

## Frequently Asked Questions

### 1. Does `datetime.now()` return the same time zone every time?

Yes, `datetime.now()` without parameters always returns the current local time based on the system's timezone settings. To get time in a specific timezone, pass a timezone object as the `tz` parameter.

### 2. Can I use `datetime.now()` to get UTC time?

While `datetime.utcnow()` is still available, it returns a naive UTC time. For timezone-aware applications, use `datetime.now(timezone.utc)` instead.

### 3. What happens if the system clock changes while my program is running?

`datetime.now()` reflects the current system time, so if the system clock is adjusted, subsequent calls will return the new time. This can affect time-based calculations in long-running applications.

### 4. Is `datetime.now()` thread-safe?

Yes, `datetime.now()` is thread-safe and can be called from multiple threads simultaneously without causing race conditions or data corruption.
Loading