熊猫datetime到unix时间戳记秒

时间:2019-01-22 17:23:53

标签: python pandas datetime

根据pandas.to_datetime的官方文档,我们可以说

unit : string, default ‘ns’
  arg的

单位(D,s,ms,us,ns)表示单位,它是整数或   浮点数。这将基于原点。 示例,带有   unit ='ms'和origin ='unix'(默认值),这将计算出   Unix纪元开始的毫秒数。

所以当我这样尝试时,

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'],unit='ms',origin='unix')
print(df)
print(df_unix_sec)

                 time
0   2019-01-15 13:25:43
0   2019-01-15 13:25:43
Name: time, dtype: datetime64[ns]

后一输出不变。每次显示日期时间值,而不是第二个unix纪元开始的毫秒数。这是为什么?我想念什么吗?

4 个答案:

答案 0 :(得分:7)

我认为您误解了该论据的含义。 <?php $target_dir = "data/temp/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo $_SERVER['SERVER_NAME']."/data/temp/". basename( $_FILES["fileToUpload"]["name"]); } else { echo "Sorry, there was an error uploading your file."; } } ?> 的目的是将整数时间戳记转换为 origin='unix',而不是相反。

datetime

相反,您可以通过转换为整数(获取纳秒)并除以10 9 来获得时间戳。

pd.to_datetime(1.547559e+09, unit='s', origin='unix') 
# Timestamp('2019-01-15 13:30:00')

答案 1 :(得分:4)

您可以使用 timestamp() method 将 POSIX 时间戳作为浮点数返回:

pd.Timestamp('2021-04-01').timestamp()

[Out]:
1617235200.0

pd.Timestamp('2021-04-01 00:02:35.234').timestamp()

[Out]:
1617235355.234

答案 2 :(得分:-1)

如果您要从数据框中访问特定的datetime64对象,熊猫很可能会返回一个Timestamp对象,这实际上就是熊猫存储datetime64对象的方式。

您可以使用pd.Timestamp.to_datetime64()对象的pd.Timestamp方法将其转换为numpy.datetime64精度的ns对象。

答案 3 :(得分:-1)

pandas Timestamp 的

value 属性保存了 unix 纪元。该值以纳秒为单位。所以你可以通过 1e3 或 1e6 转换为 ms 或 us。检查下面的代码。

import pandas as pd
date_1 = pd.to_datetime('2020-07-18 18:50:00')
print(date_1.value)