How to convert milliseconds to date and time format? - python

I have a value in milliseconds in a Python program. For example: 1557975599999
And I would like to convert it to a string with days and hours, minutes, seconds. How can I do this?

To convert unix timestamp to datetime, you can use datetime.fromtimestamp(). The only problem, that your timestamp is in miliseconds, but function expect timestamp in seconds. To cut miliseconds you can divide timestamp to 1000.
Code:
from datetime import datetime
a = 1557975599999
date = datetime.fromtimestamp(a // 1000)
print(date)
Output:
2019-05-16 05:59:59
Upd.
#Daniel in comments noticed that fromtimestamp() accept floats, so we can save miliseconds from original timestamp. All we need is just to remove one symbol :D
date = datetime.fromtimestamp(a / 1000)

With Pandas’ to_datetime()
import pandas as pd
pd.to_datetime(a, unit='ms')
# Or with a dataframe(column):
df['date'] = pd.to_datetime(df['Millisecond_time'], unit='ms')

Related

Unix timestamp conversion to time with microsecond accuracy of seconds

I have 1000 of UYC timestamps in csv file, I want to convert it into date and time but I am only interested in second like
Timestamps= 1666181576.26295,
1666181609.54292
19/10/2022 15:45:25.34568
from that I only have interest in 25.34568 seconds, also the numbers after points. How can I get this type of conversion in python? Mostly the search on the internet is interested in conversation from UTC to time and date but I also want precision in seconds.
from datetime import datetime
from decimal import Decimal
ts = 1666181576.26295
timestamp = datetime.fromtimestamp(ts)
result = timestamp.second + Decimal(timestamp.microsecond)/1000000
print(result)
Will result in 56.26295
You can use datetime,
from datetime import datetime
ts = 1666181576.26295
mseconds = datetime.utcfromtimestamp(ts).microsecond
Simplest way I can see to do this is by splitting the timestamp to output everything from seconds onwards
timestamp = 1666181609.54292
temp = datetime.utcfromtimestamp(timestamp)
output = str(temp)
print(output[17:])

Convert two timestamps to time elapses in Python

I'm trying to get the time elapsed between two string timestamps in my Python code.
Example:
Time Started: "2022-01-07 14:30"
Time Ended: "2022-01-07 15:45"
I want the answer to return as an int in number of minutes.
So, in this example it would be 75 since that is the number of minutes elapsed between the starting and ending timestamps.
You don't appear to have tried anything. Start with this:
Call datetime.strptime() to convert to datetime objects
Subtract the objects to get a timedelta
Divide timedelta.total_seconds() by sixty to get the number of minutes
from datetime import datetime
class Convert:
def main(start,end):
dt1=datetime.strptime(start, '%Y-%d-%m %H:%M')
dt2=datetime.strptime(end, '%Y-%d-%m %H:%M')
time1=str(dt1.time()).split(":")
time2=str(dt2.time()).split(":")
for i in range(0,len(time1)):
time1[i]=int(time1[i])
for j in range(0,len(time2)):
time2[j]=int(time2[j])
print(time1)
hour_to_min1=time1[0]*60+time1[1]+time1[2]
hour_to_min2=time2[0]*60+time2[1]+time2[2]
print(hour_to_min1)
print(hour_to_min2)
total_time_taken=hour_to_min2-hour_to_min1
print(f"The total time taken is {total_time_taken} minutes")
start=str(input("Enter datetime in the format yyyy-mm-dd hh:mm:ss"))
end=str(input("Enter datetime in the format yyyy-mm-dd hh:mm:ss"))
(Convert.main(start,end))
This was too simple....:)

Convert time zone date column to timestamp format

I have column containing dates in format as seen here....
2021-09-02 06:00:10.474000+00:00
However, I need to convert this column into a 13 numbered timestamp.
I have tried...
df['date_timestamp'] = df[['date']].apply(lambda x: x[0].timestamp(), axis=1).astype(int)
...but this is not producing a 13 numbered timestamp, just 10 numbers instead.
How can get it to spit a 13 numbered timestamp?
you parse to datetime, take the int64 representation and divide that by 1e6 to get Unix time in milliseconds since the epoch (1970-01-01 UTC). Ex:
import numpy as np
import pandas as pd
# string to datetime
s = pd.to_datetime(["2021-09-02 06:00:10.474000+00:00"])
# datetime to Unix time in milliseconds
unix = s.view(np.int64)/1e6
print(unix[0])
# 1630562410473.9998
The standard int64 representation is nanoseconds; so divide by 1e3 if you need microseconds.

Converting Epoch time format to standard time format

I am having an issue with converting the Epoch time format 1585542406929 into the 2020-09-14 Hours Minutes Seconds format.
I tried running this, but it gives me an error
from datetime import datetime
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
datetime.utcfromtimestamp(df2.timestamp_ms).strftime('%Y-%m-%d %H:%M:%S')
error : cannot convert the series to <class 'int'>
What am I not understanding about this datetime function? Is there a better function that I should be using?
edit: should mention that timestamp_ms is my column from my dataframe called df.
Thanks to #chepner for helping me understand the format that this is in.
A quick solution is the following:
# make a new column with Unix time as #ForceBru mentioned
start_date = '1970-01-01'
df3['helper'] = pd.to_datetime(start_date)
# convert your column of JSON dates / numbers to days
df3['timestamp_ms'] = df3['timestamp_ms'].apply(lambda x: (((x/1000)/60)/60/24))
# add a day adder column
df3['time_added'] = pd.to_timedelta(df3['timestamp_ms'],'d')
# add the two columns together
df3['actual_time'] = df3['helper'] + df3['time_added']
Note that you might have to subtract some time off from the actual time stamp. For instance, I had sent my message at 10: 40 am today when it is central time (mid west USA), but the timestamp was putting it at 3:40 pm today.

How to convert millisecond time stamp to normal date in Python?

I have a data frame with a column with values in millisecond time stamp.(df['Millisecond'])
What I want to do is to convert all values of that column into normal dates. Ex. 2017-04-27 04:55:00
You need python's datetime package to do that:
import datetime
date = datetime.datetime.fromtimestamp(milliseconds/1000.0)
date = date.strftime('%Y-%m-%d %H:%M:%S')
you can do this by using to_datetime function https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html.
df['Millisecond'] = pd.to_datetime(df['Millisecond'], unit='ms')

Categories