Python's datetime module high-level overview

[219 views]




In this tutorial we will learn how to convert a Unix timestamp into a human readable date with Python language.

Pythons datetime module high-level overview

As you've likely already seen, Unix timestamps are not easily understandable by humans.

For example, it's not straightforward or intuitive for humans to look at the number 1668614065 and realize that it equates to Wednesday, November 16, 2022 3:54:25 PM UTC-0.

Luckily, Python language makes it super easy for us to convert Unix timestamps to human readable dates!

What is a Unix timestamp?

Unix time is a unique date and time representation widely used in computing. It measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970, the beginning of the Unix epoch. Reference: Unix time – Wikipedia

A timestamp is a number used to represent date and time. Unix time, or Unix timestamp, is such a timestamp commonly used in Unix-like operating systems.

Typically, you'll obtain a Unix timestamp by:

  • Making a call to Python's time.time() function
  • Read a Unix timestamp from a database
  • Parsing log files that contain Unix timestamps
  • Working with Pandas data frames that contain Unix timestamps
Exactly how you obtain a Unix timestamp is typically application-specific.

Converting Unix timestamps to human readable dates with Python

We are now ready to learn how to convert Unix timestamps to human readable dates with Python:

# import the necessary packages from datetime import datetime from datetime import timezone # set the unix timestamp to be March 3rd, 1998 UTC unix_ts = 888888000 # convert the unix timestamp to a datetime object (the *problem* with # this approach is that a timezone wasn't supplied so your system will # convert the datetime to your local time, which may or may not be what # you intend) dt = datetime.fromtimestamp(unix_ts) print(dt)

We start off by initializing our Unix timestamp to be 888888000.
This value equates to March 3rd, 1998 at midnight UTC.
We then convert our Unix timestamp to a human readable datetime object via the datetime.from_timestamp function.

The output follows:
$ python unix_ts_to_human_readable.py 1998-03-03 06:50:00

However, we have a bit of a problem here…
Why is Python reporting the date to be March 3rd, 1998 around 6:50 ?
Didn't I just say that the intended result should be March 3rd, 1998 at midnight?
What went wrong?
The problem here is the ambiguity in time zone.
If we do not provide a time zone to fromtimestamp, then Python will default to using our system's time zone (which may or may not be what you want).
Since I'm on the east coast of the United States (UTC-5), Python took the Unix timestamp of 888888000 and converted it to a datetime object, assuming that I wanted the datetime in the UTC-5 time zone.
Again, the automatic time zone inference (based on the locale of your machine) may or may not be what you want here…
…but the best way to avoid the ambiguity is to simply operate in the UTC-0 time zone:

# the best way to avoid the ambiguity is to work in UTC time, which # produces the intended result dt = datetime.fromtimestamp(unix_ts, tz=timezone.utc) print(dt)
This code block is identical to the one above, except now that I'm supplying the time zone parameter ( tz) to be timezone.utc.
The output of this code block provides the correct result of March 3rd, 1998 at midnight UTC.
1998-03-03 00:00:00+00:00
At this point our dt variable is a proper datetime object, implying that we can easily access any and all datetime attributes like year, month day, etc.:
# now that the unix timestamp has been converted to a datetime object # we can access the year, month, day, etc. attributes as we normally # would print("year: {}".format(dt.year)) print("month: {}".format(dt.month)) print("day: {}".format(dt.day)) print("hour: {}".format(dt.hour)) print("minute: {}".format(dt.minute)) print("second: {}".format(dt.second)) print("timezone: {}".format(dt.tzname()))

Here you can see the output of each of these datetime attributes, all parsed from our original input Unix timestamp:
year: 1998 month: 3 day: 3 hour: 0 minute: 0 second: 0 timezone: UTC

Also take note that Python knows the time zone is UTC due to us supplying the timezone.utc parameter when parsing the Unix timestamp via fromtimestamp.
Given the parsed datetime object, we can format it in a variety of human readable ways using the strftime method:
# from there we can format the date in a variety of human-readable formats print(dt.strftime("%D")) print(dt.strftime("%b %d %Y")) print(dt.strftime("%Y-%m-%d %H:%M"))

Thus producing the following output:
03/03/98 Mar 03 1998 1998-03-03 00:00

I think you'll agree with me when I say that these examples are way more human readable than the original input Unix timestamp of 888888000.

                  Liked Article? Please Buy me a Tea 😭





Learn Python in a Week and Master It

Comments







Search
Need Programming Help??


Below Offers ends in












VPN Pro Secure and Fast v3.0.8 Premium Mod Apk Download

Quiz For You:

Search Tags