How to Convert Integer Timestamp into a Datetime

How to convert integer timestamp into a datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

How to convert integer into date object python?


I would suggest the following simple approach for conversion:

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:

date += timedelta(days=10)
date -= timedelta(days=5)

And convert back using:

s = date.strftime("%Y%m%d")

To convert the integer to a string safely, use:

s = "{0:-08d}".format(i)

This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).

Further reference: datetime objects, timedelta objects

pandas convert from datetime to integer timestamp

You can typecast to int using astype(int) and divide it by 10**9 to get the number of seconds to the unix epoch start.

import pandas as pd
df = pd.DataFrame({'time': [pd.to_datetime('2019-01-15 13:25:43')]})
df_unix_sec = pd.to_datetime(df['time']).astype(int)/ 10**9
print(df_unix_sec)

how to convert Integer values into timestamp format?

If you have a duration in minutes. You could use DateInterval like this.

$yourDate = new DateTime('2021-01-01 00:00:00');
$durationInMinutes = 4;

$interval = new DateInterval("PT{$durationInMinutes}M");
$yourDate->add($interval);

echo $yourDate->format('Y-m-d H:i:s');

https://www.php.net/manual/en/dateinterval.construct.php

Convert time zone date column to timestamp format

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.

python Incorrect date when converting unix time to utc time

The timestamp you've provided (1633438809404) is a timestamp in milliseconds, yes? If so, then divide it by 1000 before providing it to datetime.datetime.fromtimestamp (which expects a timestamp in seconds):

>>> datetime.fromtimestamp(1633438809404/1000)
datetime.datetime(2021, 10, 5, 9, 0, 9, 404000)

or, when using pandas.to_datetime, ensure you use unit='ms':

>>> timestamp = 1633438809404
>>> unix_conversion=pandas.to_datetime(timestamp, unit='ms')
>>> unix_conversion
Timestamp('2021-10-05 13:00:09.404000')


Related Topics



Leave a reply



Submit