Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# `call-datetime-strptime-without-zone` (`DTZ007`)

```toml
lint.select = ["DTZ007"]
```

## Replacing fields before converting the timezone

Calling `astimezone` produces an aware datetime even when one or more `replace` calls precede it.

```py
from datetime import datetime, timezone

datetime.strptime("2026", "%Y").replace(microsecond=0).astimezone()
datetime.strptime("2026", "%Y").replace(hour=12).replace(minute=30).astimezone(timezone.utc)
datetime.strptime("2026", "%Y").replace(tzinfo=None).astimezone()
```

## Replacements that leave a naive datetime

A replacement without a timezone conversion still produces a naive datetime.

```py
from datetime import datetime

datetime.strptime("2026", "%Y").replace(microsecond=0) # error: [call-datetime-strptime-without-zone]
datetime.strptime("2026", "%Y").replace(tzinfo=None) # error: [call-datetime-strptime-without-zone]
```

## Passing a method to another call

Passing the `replace` method to another object's method does not convert the parsed datetime.

```py
from datetime import datetime

def convert(converter):
converter.replace(datetime.strptime("2026", "%Y").replace).astimezone() # error: [call-datetime-strptime-without-zone]
```
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;

use crate::rules::flake8_datetimez::helpers::DatetimeModuleAntipattern;
use crate::rules::flake8_datetimez::helpers::{self, DatetimeModuleAntipattern};

/// ## What it does
/// Checks for uses of `datetime.datetime.strptime()` that lead to naive
Expand Down Expand Up @@ -104,6 +104,10 @@ pub(crate) fn call_datetime_strptime_without_zone(checker: &Checker, call: &ast:
return;
}

if helpers::followed_by_astimezone(checker) {
return;
}

// Does the `strptime` call contain a format string with a timezone specifier?
if let Some(expr) = call.arguments.args.get(1) {
match expr {
Expand Down Expand Up @@ -155,10 +159,6 @@ fn find_antipattern(
let Some(Expr::Attribute(ast::ExprAttribute { attr, .. })) = parent else {
return Some(DatetimeModuleAntipattern::NoTzArgumentPassed);
};
// Ex) `datetime.strptime(...).astimezone()`
if attr == "astimezone" {
return None;
}
if attr != "replace" {
return Some(DatetimeModuleAntipattern::NoTzArgumentPassed);
}
Expand Down
Loading