How to include "origin" into "fromtimestamp" function of "datetime" module
Question:
I want the program to display time stamp, when seconds are given as input. But the origin year in jupyter notebook starts from 1970-01-01. I want to make the origin as 1980-01-01. Can somebody help.
I tried this, but how can i include the origin part to this slice of code:
datetime.fromtimestamp(500021).strftime("%d-%m-%Y %I:%M:%S")
Answers:
By converting the origin date as seconds and adding it will help in this case:
datetime.fromtimestamp(500021 + datetime(1980, 1, 1, 0, 0, 0).timestamp()).strftime("%d-%m-%Y %I:%M:%S")
You should add difference (in seconds) between 01-01-1970
and 01-01-1980
from your timestamp.
You can get it like this:
td1 = datetime.strptime("01-01-1970", "%d-%m-%Y")
td2 = datetime.strptime("01-01-1980", "%d-%m-%Y")
print((td2 - td1).total_seconds())
# Output is 315532800.0
So after you got it you can define your own function:
def from_timestamp(ts):
return datetime.fromtimestamp(ts + 315532800.0).strftime("%d-%m-%Y %I:%M:%S")
In UTC timezone you will get following outputs:
print(datetime.fromtimestamp(0).strftime("%d-%m-%Y %I:%M:%S"))
# 01-01-1970 00:00:00
print(from_timestamp(0))
# 01-01-1980 00:00:00
print(from_timestamp(datetime.now().timestamp()))
# 21-12-2032 01:29:04
print(from_timestamp(500021))
# 06-01-1980 06:53:41
I want the program to display time stamp, when seconds are given as input. But the origin year in jupyter notebook starts from 1970-01-01. I want to make the origin as 1980-01-01. Can somebody help.
I tried this, but how can i include the origin part to this slice of code:
datetime.fromtimestamp(500021).strftime("%d-%m-%Y %I:%M:%S")
By converting the origin date as seconds and adding it will help in this case:
datetime.fromtimestamp(500021 + datetime(1980, 1, 1, 0, 0, 0).timestamp()).strftime("%d-%m-%Y %I:%M:%S")
You should add difference (in seconds) between 01-01-1970
and 01-01-1980
from your timestamp.
You can get it like this:
td1 = datetime.strptime("01-01-1970", "%d-%m-%Y")
td2 = datetime.strptime("01-01-1980", "%d-%m-%Y")
print((td2 - td1).total_seconds())
# Output is 315532800.0
So after you got it you can define your own function:
def from_timestamp(ts):
return datetime.fromtimestamp(ts + 315532800.0).strftime("%d-%m-%Y %I:%M:%S")
In UTC timezone you will get following outputs:
print(datetime.fromtimestamp(0).strftime("%d-%m-%Y %I:%M:%S"))
# 01-01-1970 00:00:00
print(from_timestamp(0))
# 01-01-1980 00:00:00
print(from_timestamp(datetime.now().timestamp()))
# 21-12-2032 01:29:04
print(from_timestamp(500021))
# 06-01-1980 06:53:41