- How to Convert Epoch to Datetime in Python
- What is Epoch Time in Python
- Basic Conversion from Epoch to Datetime in Python
- Example: Convert Epoch to Datetime
- Python Convert Epoch to Datetime with Timezone
- Example: Convert Epoch to Datetime in a Specific Timezone
- Convert Epoch Milliseconds to Datetime in Python
- Example: Convert Epoch in Milliseconds to Datetime
- Conclusion
- time — Time access and conversions¶
- Functions¶
How to Convert Epoch to Datetime in Python
Converting epoch time to datetime is a common task in Python. In this tutorial, we will learn how to perform this conversion in different scenarios. This tutorial is comprehensive and covers Python epoch time, converting epoch to datetime with timezone, and converting epoch milliseconds to datetime in Python.
What is Epoch Time in Python
Epoch time, also known as UNIX time, is a system for tracking time that represents the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC) on Thursday, 1 January 1970, excluding leap seconds. It is widely used in computer systems for recording time.
In Python, you can obtain the current epoch time using the time module:
import time epoch_time = time.time() print(f"Current epoch time: ")
Basic Conversion from Epoch to Datetime in Python
To convert epoch time to datetime in Python, we can use the datetime module. This module has a method called fromtimestamp() which takes an epoch timestamp as input and returns a datetime object.
Example: Convert Epoch to Datetime
import time from datetime import datetime # Getting current epoch time epoch_time = time.time() # Converting epoch time to datetime datetime_object = datetime.fromtimestamp(epoch_time) print(f"Epoch time: ") print(f"Datetime: ")
You can see the output in the screenshot below:
Python Convert Epoch to Datetime with Timezone
When converting epoch time to datetime, you may also need to consider time zones. Python’s datetime module supports time zones through the pytz library. To convert epoch time to datetime with timezone, you can use the fromtimestamp() method of the datetime module, with the tz parameter.
Example: Convert Epoch to Datetime in a Specific Timezone
import time from datetime import datetime import pytz # Getting current epoch time epoch_time = time.time() # Define a timezone timezone = pytz.timezone('US/Eastern') # Convert epoch to datetime with timezone datetime_with_timezone = datetime.fromtimestamp(epoch_time, tz=timezone) print(f"Epoch time: ") print(f"Datetime with timezone: ")
You can see the screenshot below:
Convert Epoch Milliseconds to Datetime in Python
Sometimes, the epoch time might be given in milliseconds instead of seconds. Since fromtimestamp() expects the epoch time in seconds, you will need to convert milliseconds to seconds before converting it to datetime in Python.
Example: Convert Epoch in Milliseconds to Datetime
from datetime import datetime # Epoch time in milliseconds epoch_milliseconds = 1627939200000 # Convert milliseconds to seconds epoch_seconds = epoch_milliseconds / 1000.0 # Convert epoch time to datetime datetime_object = datetime.fromtimestamp(epoch_seconds) print(f"Epoch time in milliseconds: ") print(f"Datetime: ")
Check out the screenshot below:
Conclusion
This tutorial has provided you with comprehensive knowledge on how to convert epoch time to datetime in Python. We covered how to perform basic conversions using the fromtimestamp() method of the datetime module, and also delved into converting epoch time with timezones and converting epoch milliseconds to datetime.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
time — Time access and conversions¶
This module provides various time-related functions. For related functionality, see also the datetime and calendar modules.
Although this module is always available, not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.
An explanation of some terminology and conventions is in order.
- The epoch is the point where the time starts, the return value of time.gmtime(0) . It is January 1, 1970, 00:00:00 (UTC) on all platforms.
- The term seconds since the epoch refers to the total number of elapsed seconds since the epoch, typically excluding leap seconds. Leap seconds are excluded from this total on all POSIX-compliant platforms.
- The functions in this module may not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for 32-bit systems, it is typically in 2038.
- Function strptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.
- UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or GMT). The acronym UTC is not a mistake but a compromise between English and French.
Changed in version 3.3: The struct_time type was extended to provide the tm_gmtoff and tm_zone attributes when platform supports corresponding struct tm members.
Changed in version 3.6: The struct_time attributes tm_gmtoff and tm_zone are now available on all platforms.
Functions¶
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: ‘Sun Jun 20 23:21:05 1993’ . The day field is two characters long and is space padded if the day is a single digit, e.g.: ‘Wed Jun 9 04:26:40 1993’ .
If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime() .
Unlike the C function of the same name, asctime() does not add a trailing newline.
Return the clk_id of the thread-specific CPU-time clock for the specified thread_id.
Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value for thread_id.
Passing an invalid or expired thread_id may result in undefined behavior, such as segmentation fault.
See the man page for pthread_getcpuclockid(3) for further information.
Return the resolution (precision) of the specified clock clk_id. Refer to Clock ID Constants for a list of accepted values for clk_id.
Return the time of the specified clock clk_id. Refer to Clock ID Constants for a list of accepted values for clk_id.
Use clock_gettime_ns() to avoid the precision loss caused by the float type.
Similar to clock_gettime() but return time as nanoseconds.
Set the time of the specified clock clk_id. Currently, CLOCK_REALTIME is the only accepted value for clk_id.
Use clock_settime_ns() to avoid the precision loss caused by the float type.
Similar to clock_settime() but set time with nanoseconds.
Convert a time expressed in seconds since the epoch to a string of a form: ‘Sun Jun 20 23:21:05 1993’ representing local time. The day field is two characters long and is space padded if the day is a single digit, e.g.: ‘Wed Jun 9 04:26:40 1993’ .
If secs is not provided or None , the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)) . Locale information is not used by ctime() .
time. get_clock_info ( name ) ¶
Get information on the specified clock as a namespace object. Supported clock names and the corresponding functions to read their value are:
- ‘monotonic’ : time.monotonic()
- ‘perf_counter’ : time.perf_counter()
- ‘process_time’ : time.process_time()
- ‘thread_time’ : time.thread_time()
- ‘time’ : time.time()
The result has the following attributes:
- adjustable: True if the clock can be changed automatically (e.g. by a NTP daemon) or manually by the system administrator, False otherwise
- implementation: The name of the underlying C function used to get the clock value. Refer to Clock ID Constants for possible values.
- monotonic: True if the clock cannot go backward, False otherwise
- resolution: The resolution of the clock in seconds ( float )
Convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None , the current time as returned by time() is used. Fractions of a second are ignored. See above for a description of the struct_time object. See calendar.timegm() for the inverse of this function.
Like gmtime() but converts to local time. If secs is not provided or None , the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.
localtime() may raise OverflowError , if the timestamp is outside the range of values supported by the platform C localtime() or gmtime() functions, and OSError on localtime() or gmtime() failure. It’s common for this to be restricted to years between 1970 and 2038.
This is the inverse function of localtime() . Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time() . If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use monotonic_ns() to avoid the precision loss caused by the float type.
Changed in version 3.5: The function is now always available and always system-wide.
Changed in version 3.10: On macOS, the function is now system-wide.
Similar to monotonic() , but return time as nanoseconds.
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use perf_counter_ns() to avoid the precision loss caused by the float type.
Changed in version 3.10: On Windows, the function is now system-wide.
Similar to perf_counter() , but return time as nanoseconds.
Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use process_time_ns() to avoid the precision loss caused by the float type.
Similar to process_time() but return time as nanoseconds.
Suspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time.
If the sleep is interrupted by a signal and no exception is raised by the signal handler, the sleep is restarted with a recomputed timeout.
The suspension time may be longer than requested by an arbitrary amount, because of the scheduling of other activity in the system.
On Windows, if secs is zero, the thread relinquishes the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution. On Windows 8.1 and newer the implementation uses a high-resolution timer which provides resolution of 100 nanoseconds. If secs is zero, Sleep(0) is used.
- Use clock_nanosleep() if available (resolution: 1 nanosecond);
- Or use nanosleep() if available (resolution: 1 nanosecond);
- Or use select() (resolution: 1 microsecond).
Changed in version 3.11: On Unix, the clock_nanosleep() and nanosleep() functions are now used if available. On Windows, a waitable timer is now used.
Changed in version 3.5: The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale).
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. format must be a string. ValueError is raised if any field in t is outside of the allowed range.
0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one.
The following directives can be embedded in the format string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the strftime() result:
Locale’s abbreviated weekday name.