Python 3 How to convert date to Unix timestamp

You can use several Python modules to convert a string date/datetime to a timestamp. Depending on the date type:

  • string representing a date
  • datetime

You have different solutions. Lets see an example when the date is stored as a string. This solution works for Python 2 and 3. It remove the time and convert the string to datetime. After that apply the format for unix datetime:

import datetime
my_date = '18/10/2018'
print(int(datetime.datetime.strptime(my_date, '%d/%m/%Y').strftime("%s")))



Next example is using different approach:

from datetime import timezone
dt = datetime.datetime(2018, 10, 18)
unix_ts_utc = dt.replace(tzinfo=timezone.utc).timestamp()
unix_ts = dt.timestamp()



In this case we assume that the date is stored as datetime. The second line of the code create a date time from the year, month and the day. This function returns the time since epoch for that datetime object. You can see the difference in using a time zone from this example. This code example works only for python 3.

You can create a datetime also using formatting like:

datetime.datetime.strptime('16/08/2018', '%d%m%Y')

The third option is by using dateutil and parser. You can see the example below:

import dateutil.parser
my_date = '18/10/2018'
my_ts = dateutil.parser.parse(my_date, dayfirst=True).timestamp()



This method parse your date by taking into account that your date has day in the beginning. Then conver it to a timestamp.

Note 1: Sometimes you may need to multiply the timestamp on 1000 in order to work for some systems.

Note 2: The unix timestamp(POSIX time) represents the number of seconds that have passed between the beginning of the unix epoch and the date specified.

Related Article