how to convert datetime to unix timestamp in python code example

Example 1: unix to date python

>>> from datetime import datetime
>>> ts = int("1284101485")

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
>>> print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
#'%Y' will be replaced by the year '%m' by the month '%d; by the day and so on 
#You move these how you want in the string, other characters will be ignored!
... '2010-09-10 06:51:25'

Example 2: convert to timestamp python

import datetime
date = '18/05/2020 - 18:05:12'

# convert string to datetimeformat
date = datetime.datetime.strptime(date, "%d %m %Y - %H:%M:%S"")

# convert datetime to timestamp
date = datetime.datetime.timestamp(date)

Example 3: convert integer unix to timestamp python

import datetime
print(
    datetime.datetime.fromtimestamp(
        int("1284105682")
    ).strftime('%Y-%m-%d %H:%M:%S')
)

Example 4: get datetime from unix timestamp python3

from datetime import datetime

timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)

print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))

Tags:

Java Example