根据当前日期写入 S3 密钥

时间:2021-03-17 17:23:29

标签: python amazon-web-services amazon-s3 python-s3fs

我正在尝试使用 Python 中的 S3FileSystem 在 S3 中编写一个 csv。每次写入时,我都会在当前日期的键 ('%Y-%m -%d') 以便按日期组织数据。我在想这样的话,数据将按日期组织,并且不会在同一天创建新的密钥。

file_name_s3 = f"{strftime('%Y-%m-%d', gmtime())}/test_feature-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}.csv"

但看起来我跑了。如果我在今天的日期 (2021-03-17) 运行以下代码,则第一次创建此密钥 2021-03-17。下次它会创建一个新密钥 2021-03-18,即使我在同一天运行它。

谁能建议如何解决这个问题?

完整代码如下

file_name_s3 = f"{strftime('%Y-%m-%d', gmtime())}/test_feature-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}.csv"
writekey = 'rca/RnD/test/'+file_name_s3
bucket = 'mybucket'


def write_to_s3(bucket, writekey, result_feature_dict):
    '''
    Writes the feature dictionary as a CSV to S3
    '''
    print("Writing to S3...")
    s3 = s3fs.S3FileSystem(anon=False)
    toCSV = []
    for key, value in result_feature_dict.items():
        toCSV.append(value)
    keys = toCSV[0].keys()
    
    with s3.open('{}/{}'.format(bucket, writekey), mode='w', newline='') as f:
        dict_writer = csv.DictWriter(f, keys)
        dict_writer.writeheader()
        dict_writer.writerows(toCSV)

更新

这确实有效。日期是 UTC,所以即使我的本地日期是相同的,日期在 UTC 中发生了变化,这造成了混乱。

0 个答案:

没有答案