How do you convert a time.struct_time object into a datetime object?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python, time.struct_time and datetime.datetime both represent time-related information, but they are designed for different APIs. struct_time is the tuple-like result you often get from the time module, while datetime gives you richer date arithmetic, formatting, and timezone support.
Converting between them is straightforward once you decide whether you want a naive local datetime, a UTC datetime, or a conversion through a Unix timestamp. The right method depends on what the original struct_time actually represents.
Build a datetime Directly from the Fields
A time.struct_time object exposes the date and clock components directly, so you can pass them into datetime.
This is the most explicit approach. It works well when you simply want a datetime with the same visible fields.
Use fromtimestamp When the struct_time Represents Local Time
If the struct_time came from time.localtime(), another common route is to convert it through a Unix timestamp.
This is useful when you want Python to interpret the value using local-time rules consistently.
The mktime function assumes the struct_time represents local time, so it is a good match for localtime() data.
Use calendar.timegm for UTC struct_time
If the struct_time came from time.gmtime(), using time.mktime() would be conceptually wrong because mktime() treats its input as local time.
For UTC data, use calendar.timegm() instead.
This preserves the UTC meaning of the original value.
Which Conversion Should You Prefer?
A practical rule is:
- if you only want the same visible fields, construct
datetime(...)directly - if you care about local-time interpretation, use
mktimeplusfromtimestamp - if the source is UTC, use
calendar.timegmplus a UTC-aware datetime
The last distinction matters because naive and timezone-aware datetimes behave differently in comparisons, formatting, and arithmetic.
Why the Distinction Matters
A struct_time by itself is not as expressive as a fully timezone-aware datetime. It contains date and clock fields plus some auxiliary information, but it is easy to lose track of whether the value was intended as local time or UTC.
That is why many bugs come from using the right conversion function on the wrong kind of struct_time.
For example:
- '
time.localtime()pairs naturally withmktime' - '
time.gmtime()pairs naturally withcalendar.timegm'
Mixing those up shifts the meaning of the moment in time.
A Helper Function
If you do this conversion often, wrap it in a helper that makes the time basis explicit.
This makes callers choose the interpretation instead of guessing later.
Common Pitfalls
One common mistake is using time.mktime() on a struct_time that actually came from time.gmtime(). That applies local-time semantics to a UTC value and shifts the result incorrectly.
Another issue is creating a naive datetime and later treating it as if it were timezone-aware. Those are not interchangeable concepts.
It is also easy to forget that direct field construction ignores some contextual interpretation details, such as daylight-saving transitions, that a timestamp-based conversion may handle differently.
Finally, do not overcomplicate the conversion if all you need is a simple datetime with matching fields. Direct construction is often perfectly fine.
Summary
- You can convert
time.struct_timetodatetimeby passing its fields directly intodatetime(...). - If the value is local time,
time.mktime()plusdatetime.fromtimestamp()is another common approach. - If the value is UTC, use
calendar.timegm()and ideally build a timezone-aware UTC datetime. - The main design choice is whether the
struct_timeshould be interpreted as local time or UTC. - Most conversion bugs come from mixing up those two interpretations.
Related reading
- How do you create a boolean mask for a tensor in Keras?
- How do you create a daemon in Python?
- How do you create nested dict in Python?
- How do you decode Base64 data in Python?
- How do you divide each element in a list by an int?
- How do you express binary literals in Python?
- How do you generate dynamic parameterized unit tests in Python?
- How do you get a directory listing sorted by creation date in python?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.