Computer >> Computer tutorials >  >> Programming >> Python

How to convert Python datetime to epoch with strftime?


To convert python datetime to epoch with strftime you'd need to provide the strftime function with a formatting string that contains the code for formatting the date as seconds since epoch. The %s directive is used for this purpose. 

example

import datetime
timestamp = datetime.datetime(2017, 12, 1, 0, 0).strftime('%s')
print(timestamp)

Output

This will give the output −

1445212800

If you're on Python 3.3+, you can simply use the timestamp function to get the time since epoch.

 example

import datetime
timestamp = datetime.datetime(2017, 12, 1, 0, 0).timestamp()
print(timestamp)

Output

This will give the output −

1445212800