微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法从十六进制数中检索日期戳

如何解决无法从十六进制数中检索日期戳

我尝试了很多方法来完成此操作,但仍然出现错误。我做错了什么?

如果我试图用简单的字符串来完成,一切都会好的:

import pytz
from datetime import datetime

id_board = '608332c0'
df_final = datetime.fromtimestamp(int(id_board,16))
print(df_final)
output: 2021-04-23 14:49:04

但是,我确实有一个我想要获取日期戳的列表,这里是给我错误代码

import pytz
import pandas as pd
from datetime import datetime

df_final = pd.read_csv("Book1.csv")
print(df_final)

                    Card ID  # of Members
0  608332c0806da55df13b498b             2
1  60819c7ccd3a695b79f54f53             5
2  60817b9df8f5422bbaf2cff9             9
3  60806f3d24f11404f1470904             2
4  607ed78a89de73411e937655             1
5  608332e6943e7263a56fb3ff             2

x = df_final["Card ID"].str[0:8]
df_final["Created Date"] = x
print(df_final)

                   Card ID  # of Members Created Date
0  608332c0806da55df13b498b             2     608332c0
1  60819c7ccd3a695b79f54f53             5     60819c7c
2  60817b9df8f5422bbaf2cff9             9     60817b9d
3  60806f3d24f11404f1470904             2     60806f3d
4  607ed78a89de73411e937655             1     607ed78a
5  608332e6943e7263a56fb3ff             2     608332e6

df_final["Created Date"] = datetime.fromtimestamp(int(x,16))
print(df_final)

Traceback (most recent call last):
  File "c:\Users\xxxxx\Desktop\Manual Formulas 1\hexa.py",line 17,in <module>
    df_final["Created Date"] = datetime.fromtimestamp(int(x,16))
TypeError: int() can't convert non-string with explicit base

我已经尝试了许多我读过的“修复”,但仍然相同。我还尝试在行上循环,但出现以下错误

invalid literal for int() with base 16

感谢您的帮助! 乔。

解决方法

我知道您认为您正在将字符串转换为整数。
但是,您实际上并没有将字符串转换为整数。

考虑以下代码:

my_favorite_number = int("AF91",16)
print("THE FIRST CONVERSION WORKED\n")

my_favorite_number = int(8234,16)
print("THE SECOND CONVERSION WORKED")  

控制台输出如下:

THE FIRST CONVERSION WORKED

Traceback (most recent call last):
  File "D:/python_sandbox/fgdfgdf.py",line 6,in <module>
    my_favorite_number = int(8234,16)
TypeError: int() can't convert non-string with explicit base

要注意的关键是 int() can't convert non-string

请先将您的输入转换为字符串,然后再将其转换为整数。

例如,你可以写,

numby_the_number = int(str(datum),16)
,

感谢您花时间研究我的问题。我在代码上做了更多工作,并且能够执行我正在寻找的操作。以下是用于学习目的的解决方案:

from datetime import datetime    
df_final = pd.read_csv("Book1.csv")
    get_date = df_final["Card ID"].str[0:8].apply(lambda x: datetime.fromtimestamp(int(x,16)))
    df_final["Nueva"] = get_date
    print(df_final)
                    Card ID  # of Members               Nueva
0  608332c0806da55df13b498b             2 2021-04-23 14:49:04
1  60819c7ccd3a695b79f54f53             5 2021-04-22 09:55:40
2  60817b9df8f5422bbaf2cff9             9 2021-04-22 07:35:25
3  60806f3d24f11404f1470904             2 2021-04-21 12:30:21
4  607ed78a89de73411e937655             1 2021-04-20 07:30:50
5  608332e6943e7263a56fb3ff             2 2021-04-23 14:49:42

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。