开发者

Seconds since epoch to relative date

I'm working with dates since epoch, and already got, for example:

date = 6928727.56235

I'd like to transform this into another relative format, so that I'll be able to transform this into something relative to epoch.

Using time.gmtime(date), it returned

year=1970, mon=3, day=开发者_如何学C22, hour=4, min=38, sec=47

I think epoch starts in '01/01/1970 00:00:00', so the method should return the relative date in something like:

'2 months 21 days 04:38:47'

Anything that help?


The method should return the relative date in something like: '2 months 22 days 04:38:47'

You can't do that, since a month is between 28 and 31 days long. The statement "2 months and 22 days" could mean anything between 81 and 84 days. (Or between 78 and 84 days, if the months doesn't have to be consecutive).

So what you want is simply nonsensical. A relative date time can only be counted in days, hours and seconds, until the difference becomes so big that the amount of days no longer matters, in which case you can start counting in months or years (but then you can't include days anymore).

So you can say "five years and two months", or "80 days and three hours", or "two hundred years". But you can not say "two months and three days" or "five years and 20 days". The statements simply make no sense.

Therefore, the correct answer is indeed eumiros

timedelta(seconds=6928727.56235)

But now you also know why.

(Unless of course, you with month actually mean moon-cycles, which do have a fixed length. :))


from datetime import timedelta

a = timedelta(seconds=6928727.56235)

# a is now datetime.timedelta(80, 16727, 562350)

print "%d days %02d:%02d:%02d" % (a.days, a.seconds / 3600, (a.seconds / 60) % 60, a.seconds % 60)

Returns 80 days 04:38:47, which is correct, but not exactly what OP wanted (80 days instead of 2 months 21 days).


time.gmtime returns a ParseTuple object and you can use the individual elements of the tuple do your calculation. Something like this

>>> time_epoch = time.gmtime(0)
>>> time_at_hand = time.gmtime(6928727.56235)
>>> print "It's been %d days somewhat like  %d months, %d days and %d hours, %d  minutes, %d seconds " % (time_at_hand.tm_yday - time_epoch.tm_yday, time_at_hand.tm_mon - time_epoch.tm_mon , time_at_hand.tm_mday - time_epoch.tm_mday, time_at_hand.tm_hour - time_epoch.tm_hour, time_at_hand.tm_min - time_epoch.tm_min, time_at_hand.tm_sec - time_epoch.tm_sec)
It's been 80 days somewhat like  2 months, 21 days and 4 hours, 38  minutes, 47 seconds 


Similar to Eumiro's Answer, but no need to divide by 60 etc - instead, use Pandas Timestamp and take the difference from beginning of epoch.

date = 6928727.56235
import pandas as pd
pd.Timestamp(datetime.fromtimestamp(date))-pd.Timestamp(datetime.fromtimestamp(0))

returns

Timedelta('80 days 04:38:47.562350')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜