What Is a Unix Timestamp and Why Use It

What is a Unix timestamp and why use it?

What is a Unix Timestamp

Simply put, the Unix timestamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the Unix timestamp is merely the number of seconds between a particular date and the Unix Epoch. It should also be pointed out that this point in time technically does not change no matter where you are located on the globe. This is very useful to computer systems for tracking and sorting dated information in dynamic and distributed applications both online and client-side. The reason why Unix timestamps are used by many webmasters is that they can represent all time zones at once. For more information, read the Wikipedia article.

What is strtotime() and how is it useful

As the name suggests, strtotime() function is used to convert a date string to a Unix timestamp (str to time).

From the [PHP manual documentation for strtotime()] 2:

strtotime — Parse about any English textual datetime description into a Unix timestamp

For example, say you wanted to get the Unix timestamp for the date 25 December 2013, then you'd use strtotime() like so:

echo strtotime("25 December 2013"), "\n";       // => 1387909800

strtotime() can also handle relative time and date formats. For example, consider the following:

echo strtotime("+1 month"), "\n";               // => 1390980039
echo strtotime("last day of next month"), "\n"; // => 1391152839

These are some basic examples. strtotime() can handle very complex date formats, too. See the documentation for more information.

When should I use a timestamp

A Unix timestamp is interpreted the same regardless of region and is calculated from the same point in time regardless of the time zone. If you have a web application that is used over multiple timezones and you need date/time to reflect individual users' settings, use a timestamp.

In the case of strtotime(), it is mostly used to convert between date formats. Since strtotime() can parse almost any date string, it's used to convert the date string into a timestamp. Once you have the timestamp, you can format it however you wish, using date(), or similar functions.

Limitations of strtotime()

On a 32-bit system, the maximum value of an integer is 2,147,483,647. The furthest time that can be represented this way is 03:14:07 UTC on Tuesday, 19 January 2038. This is also known as Year 2038 problem.

See this note in the PHP manual:

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

Use DateTime objects

If you're working with dates outside the 13 Dec 1901 to 19 Jan 2038 range, then consider using PHP's DateTime objects which can work with a much wider range of dates. DateTime can represent approximately 293 billion years in either direction.

The DateTime class is available on PHP versions >= 5.2.0. If you are running a PHP version that's above >= 5.2.0, then you should use DateTime when working with dates and times. It's the best way to go. If you're having an older PHP version, upgrade already. Anything before 5.3.0 is ancient.

  • Use either DateTime::__construct() or DateTime::createFromFormat() to create a DateTime object. Note that DateTime::createFromFormat() is only available on PHP >= 5.3. Using this method, you can parse date and time weird strings that might otherwise not be possible with strtotime()
  • Use DateTime::format() method to convert your DateTime object to any date format you might want to work with

Here are some good articles on DateTime:

  • Why PHP DateTime rocks
  • PHP The Right Way: Date and Time

And a book for the shelf:

  • php|architect's Guide to Date and Time Programming (written by Derick Rethans, who is a contributor to PHP's core date extension)

Unix timestamp: everywhere the same?

Unix timestamps are the number of seconds elapsed since 01-01-1970 00:00:00 UTC so if the system time is set correctly it should be equal everywhere.

MySQL: What's the best to use, Unix TimeStamp Or DATETIME

Timestamp (both PHP ones and MySQL's ones) are stored using 32 bits (i.e. 4 bytes) integers ; which means they are limited to a date range that goes from 1970 to 2038.

DATETIME don't have that limitation -- but are stored using more bytes (8 bytes, if I'm not mistaken)


After, between storing timestamps as seen by PHP, or timestamps as seen by MySQL :

  • using PHP timestamps means manipulations are easier from PHP -- see Date/Time Functions
  • using MySQL's timestamps means manipulations are easier from MySQL -- see 11.6. Date and Time Functions


And, for more informations between MySQL's TIMESTAMP and DATETIME datatypes, see 10.3.1. The DATETIME, DATE, and TIMESTAMP Types

Is storing a Unix timestamp a bad idea in the long term

There are 31,536,000 seconds in a year, so it will take over 269 years before another digit is added to unix timestamps.

(10,000,000,000 - 1,510,798,414) / 31,536,000 = 269.1908

So, on that count I'd say you're good for a while.

Depending on the database column type that you're using, a more immediate problem might be that from January 19, 2038 onward, you will no longer be able to store your timestamps in a signed 32 bit integer as they have a max value of 2,147,483,647.

So, I'd say: put a sticky note on your monitor to change your database column type on January 18, 2038. If you're using an unsigned 32 bit integer type, you're good until 2106.

Are unix timestamps the best way to store timestamps?

However you choose to store a timestamp, it is important to avoid regional interpretation problems and time offset problems. A Unix timestamp is interpreted the same regardless of region, and is calculated from the same point in time regardless of time zone - these are good things.

Beware storing timestamps as ambiguous strings such as 01/02/2008, since that can be interpreted as January 02, 2008 or February 01, 2008, depending on locale.

When storing hours/minutes/seconds, it is important to know "which" hour/minute/second is being specified. You can do this by including timezone information (not needed for a Unix timestamp, since it is assumed to be UTC).

However, note that Unix timestamps cannot uniquely represent some instants in time: when there is a leap second in UTC, the Unix timestamp does not change, so both 23:59:60 UTC and 00:00:00 the next day have the same Unix representation. So if you really need one second or better resolution, consider another format.

If you prefer a more human readable format for storage than a Unix timestamp, consider ISO 8601.

One technique that helps keep things straight-forward is to store dates as UTC and only apply timezone or DST offsets when displaying a date to a user.

How to represent dates before epoch as a UNIX timestamp

Unix Time is usually a 32-bit number of whole seconds from the first moment of 1970 in UTC, the epoch being 1 January 1970 00:00:00 UTC. That means a range of about 136 years with about half on either side of the epoch. Negative numbers are earlier, zero is the epoch, and positive are later. For a signed 32-bit integer, the values range from 1901-12-13 to 2038-01-19 03:14:07 UTC.

This is not written in stone. Well, it is written, but in a bunch of different stones. Older ones say 32-bit, newer ones 64-bit. Some specifications says that the meaning is "implementation-defined". Some Unix systems use an unsigned int to extend only into the future past the epoch, but usual practice has been a signed number. Some use a float rather than an integer. For details, see Wikipedia article on Unix Time, and this Question.

So, basically, your Question makes no sense. You have to know the context of your programming language (standard C, other C, Java, etc.), environment (POSIX-compliant), particular software library, or database store, or application.

Avoid Count-From-Epoch

Add to this lack of specificity the fact that a couple dozen other epochs have been used by various software systems, some extremely popular and common. Examples include January 1, 1601 for NTFS file system & COBOL, January 1, 1980 for various FAT file systems, January 1, 2001 for Apple Cocoa, and January 0, 1900 for Excel & Lotus 1-2-3 spreadsheets.

Further add the fact that different granularities of count have been used. Besides whole seconds, some systems use milliseconds, microseconds, or nanoseconds.

I recommend against tracking date-time as a count-from-epoch. Instead use specific data types where available in your programming language or database.

ISO 8601

When data types are not available, or when exchanging data, follow the ISO 8601 standard which defines sensible string formats for various kinds of date-time values.

  • Date
    • 2015-07-29
  • A date-time with an offset from UTC (Z is zero/Zulu for UTC) (note padding zero on offset)
    • 2015-07-29T14:59:08Z
    • 2001-02-13T12:34:56.123+05:30
  • Week (with or without day of week)
    • 2015-W31
    • 2015-W31-3
  • Ordinal date (day-of-year)
    • 2015-210
  • Interval
    • "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z"
  • Duration (format of PnYnMnDTnHnMnS)
    • P3Y6M4DT12H30M5S = "period of three years, six months, four days, twelve hours, thirty minutes, and five seconds"

Search StackOverflow.com for many more Questions and Answers on these topics.

Do UNIX timestamps change across timezones?

The definition of UNIX timestamp is time zone independent. The UNIX timestamp is the number of seconds (or milliseconds) elapsed since an absolute point in time, midnight of Jan 1 1970 in UTC time. (UTC is Greenwich Mean Time without Daylight Savings time adjustments.)
Regardless of your time zone, the UNIX timestamp represents a moment that is the same everywhere. Of course you can convert back and forth to a local time zone representation (time 1397484936 is such-and-such local time in New York, or some other local time in Djakarta) if you want.

The article at http://en.wikipedia.org/wiki/Unix_time is pretty impressive if you'd like a longer read.

how can i add any unix timestamp in discord.py

You can do this by using the mktime function in the time module.

import datetime
import time

def convert_to_unix_time(date: datetime.datetime, days: int, hours: int, minutes: int, seconds: int) -> str:
# Get the end date
end_date = date + datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)

# Get a tuple of the date attributes
date_tuple = (end_date.year, end_date.month, end_date.day, end_date.hour, end_date.minute, end_date.second)

# Convert to unix time
return f'<t:{int(time.mktime(datetime.datetime(*date_tuple).timetuple()))}:R>'

The returned value should like somewhat like this: <t:1655392367:R>

Pasting the returned string will give a dynamic display as shown in the image you have provided.

The mktime function returns a float value. For the datetime to be displayed dynamically, the value in between must be numbers only.

The R in the end of the returned string stands for relative. The dynamic display will be relative to current time. The other formats are t, T, d, D, f and F.



Related Topics



Leave a reply



Submit