Python
datetime
time.struct_time
programming
conversion

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.

Browse interview questions

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.

python
1import time
2from datetime import datetime
3
4st = time.localtime()
5
6dt = datetime(
7    st.tm_year,
8    st.tm_mon,
9    st.tm_mday,
10    st.tm_hour,
11    st.tm_min,
12    st.tm_sec,
13)
14
15print(st)
16print(dt)

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.

python
1import time
2from datetime import datetime
3
4st = time.localtime()
5timestamp = time.mktime(st)
6dt = datetime.fromtimestamp(timestamp)
7
8print(dt)

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.

python
1import time
2import calendar
3from datetime import datetime, timezone
4
5st = time.gmtime()
6timestamp = calendar.timegm(st)
7dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
8
9print(dt)

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 mktime plus fromtimestamp
  • if the source is UTC, use calendar.timegm plus 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 with mktime'
  • 'time.gmtime() pairs naturally with calendar.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.

python
1import calendar
2from datetime import datetime, timezone
3
4
5def struct_time_to_datetime(st, *, is_utc=False):
6    if is_utc:
7        timestamp = calendar.timegm(st)
8        return datetime.fromtimestamp(timestamp, tz=timezone.utc)
9
10    return datetime(
11        st.tm_year,
12        st.tm_mon,
13        st.tm_mday,
14        st.tm_hour,
15        st.tm_min,
16        st.tm_sec,
17    )

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_time to datetime by passing its fields directly into datetime(...).
  • If the value is local time, time.mktime() plus datetime.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_time should be interpreted as local time or UTC.
  • Most conversion bugs come from mixing up those two interpretations.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.