Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change datetime to Unix time stamp in Python

Tags:

Please help me to change datetime object (for example: 2011-12-17 11:31:00-05:00) (including timezone) to Unix timestamp (like function time.time() in Python).

like image 405
Thelinh Truong Avatar asked Dec 17 '11 05:12

Thelinh Truong


People also ask

How do I get the current UNIX timestamp in Python?

In the time module, the timegm function returns a Unix timestamp. The timetuple() function of the datetime class returns the datetime's properties as a named tuple. To obtain the Unix timestamp, use print(UTC).

How do you convert Unix time to local time in Python?

Use datetime. fromtimestamp() of the datetime module to convert Unix time (Epoch time) to datetime object. Specify Unix time as an argument. By default, it is converted to the local date and time.


1 Answers

Another way is:

import calendar from datetime import datetime d = datetime.utcnow() timestamp=calendar.timegm(d.utctimetuple()) 

Timestamp is the unix timestamp which shows the same date with datetime object d.

like image 96
Shnkc Avatar answered Oct 23 '22 08:10

Shnkc