Change datetime to Unix time stamp in Python Change datetime to Unix time stamp in Python unix unix

Change datetime to Unix time stamp in Python


Another way is:

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

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


import timeimport datetimedtime = datetime.datetime.now()ans_time = time.mktime(dtime.timetuple())


Incomplete answer (doesn't deal with timezones), but hopefully useful:

time.mktime(datetime_object.timetuple())

** Edited based on the following comment **

In my program, user enter datetime, select timezone. ... I created a timezone list (use pytz.all_timezones) and allow user to chose one timezone from that list.

Pytz module provides the necessary conversions. E.g. if dt is your datetime object, and user selected 'US/Eastern'

import pytz, calendartz = pytz.timezone('US/Eastern')utc_dt = tz.localize(dt, is_dst=True).astimezone(pytz.utc)print calendar.timegm(utc_dt.timetuple())

The argument is_dst=True is to resolve ambiguous times during the 1-hour intervals at the end of daylight savings (see here http://pytz.sourceforge.net/#problems-with-localtime).