0

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

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
CoCo
  • 93
  • 1
  • 9
  • Can you show some examples of what you expect to get as a result? – mkrieger1 Oct 29 '20 at 12:46
  • sort-of addresses this question but is very confusing to newcomers / overloaded / partly outdated in my opinion: [Converting datetime.date to UTC timestamp in Python](https://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python/8778548#8778548) – FObersteiner Oct 29 '20 at 12:52
  • Does this answer your question? [Converting datetime.date to UTC timestamp in Python](https://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python) – Brian Tompsett - 汤莱恩 Oct 29 '20 at 16:08

2 Answers2

0

Im kind of confused by what exactly it is that you want. Here is a helpful link.

Does the below do what you want?

import time

current_time = time.time() // 86400  # second in a day
print(current_time)  # returns 18564.0 i.e. the number of days since Unix epoch
0

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.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72