0

When I run time.mktime(datetime.strptime("2012-03-09", "%Y-%m-%d").timetuple())

I get the value 1331251200.0.

Now I want to know how can I invert this? So if I pass in 1331251200.0, how do I get as output 2012-03-09? I know strftime is the inverse of strptime, but I don't see how to invert the whole thing because of the timetable function.

Kashif
  • 3,063
  • 6
  • 29
  • 45
  • From the docs, looks like it's just `time.localtime`? https://docs.python.org/3/library/time.html#time.localtime – rafaelc Apr 09 '21 at 22:38
  • Yeah I have that now but I want a string output of 2012-03-09. Now I get `time.struct_time(tm_year=2012, tm_mon=3, tm_mday=9, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=69, tm_isdst=0)` as output. – Kashif Apr 09 '21 at 22:39
  • Nvm I got it. `time.strftime("%Y-%m-%d", time.localtime(time.mktime(datetime.strptime("2012-03-09", "%Y-%m-%d").timetuple())))` is what I could do. – Kashif Apr 09 '21 at 22:44
  • Does this answer your question? [Converting unix timestamp string to readable date](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date) – FObersteiner Apr 10 '21 at 08:08

1 Answers1

0

So the way to do this is by time.strftime("%Y-%m-%d", time.localtime(time.mktime(datetime.strptime("2012-03-09", "%Y-%m-%d").timetuple()))).

I didn't know strftime would turn the timetable to a string before I asked.

Kashif
  • 3,063
  • 6
  • 29
  • 45
  • Note that datetime objects have methods `timestamp` and `fromtimestamp` - seems to me as if those would make your life easier. – FObersteiner Apr 10 '21 at 08:10