Skip to content

Allow gzip mtime to be a datetime object #128584

@gchqdev227

Description

@gchqdev227

Feature or enhancement

Proposal:

Currently, the mtime optional parameter of the gzip.GzipFile class and gzip.compress function can be an float representing a Unix timestamp, or None to use the current time. I propose allowing this to also be a datetime.datetime object. All of these would then be possible:

from datetime import datetime, timezone
import gzip
import zoneinfo

compress(data)  # compress using current time
compress(data, mtime=0)  # ignore the time
compress(data, mtime=1736247159)  # specify the time with a Unix timestamp
compress(data, mtime=datetime(2025, 1, 7, tzinfo=timezone.utc))  # specify time with a datetime object
compress(data, mtime=datetime(2025, 1, 7, tzinfo=zoneinfo.ZoneInfo(key='US/Eastern')))  # specify a different timezone

This avoids users needing to cast their datetime objects into timestamps before calling compress or creating a GzipFile instance, which can lead to mistakes.

I have an initial PR for this ready to go.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions