Search code examples
python-3.xdatetimepython-datetimeepoch

Generate UNIX time for certain date in Python


I am new at python and I am trying to generate the same epoch time for entire day using datetime and time modules. So far I am not able to succeed. I have tried the same thing in javascript.

Following is code for it

var d = new Date();
var n = d.toDateString();
var myDate = new Date(n);
var todays_date = myDate.getTime()/1000.0;
console.log(todays_date)

How can I do it in python? Please help. thanks in advance


Solution

  • To get seconds since the epoch for a given date object, you can create a datetime object from the date's timetuple (hour, minutes, seconds = 0), set the time zone if required and call the timestamp() method:

    from datetime import date, datetime, timezone
    
    unix_time = datetime(*date.today().timetuple()[:6], tzinfo=timezone.utc).timestamp()
    # 1603929600.0 for 2020-10-29
    

    For the example, I use date.today() which you can replace with any other date object. You can obtain the date object of any datetime object using datetime_object.date().

    Note: I'm using tzinfo=UTC here, which is arbitrary / assumes that the input date also refers to UTC. Replace with the appropriate time zone object if needed; for that see zoneinfo. To exactly mimic your javascript code snippet, set tzinfo=None.