PySpark:如何将分钟转换为小时:分钟?

PySpark : How to convert minutes to hours : minutes?

我会将 col 以分钟为单位转换为小时:分钟

col(min)
685

我会得到

col(min) col1(h:min)
685 11:25

使用sql函数divmod分别求出商和余数,然后拼接起来

df = df.withColumn('col1', F.expr('concat(div(col, 60), ":", mod(col, 60))'))

您可以使用 .map 将数据从 RDD 转换为一个或多个列。

Python 内置函数 divmod returns 整数除法的商和余数。 divmod(a, b) 等同于 (a // b, a % b).

rdd = sc.parallelize([
    685, 180, 80
])

results = rdd.map(lambda x: divmod(x, 60))

print( results.collect() )
# [(11, 25), (3, 0), (1, 20)]

或者,如果您希望结果为 hh:mm 格式的字符串,请使用 str.format 根据您的喜好设置值的格式:

results = rdd.map(lambda x: '{:02d}:{:02d}'.format(*divmod(x, 60)))

print( results.collect() )
# ['11:25', '03:00', '01:20']

如果您想同时保留分钟数和结果 hh:mm 字符串:

results = rdd.map(lambda x: (x, '{:02d}:{:02d}'.format(*divmod(x, 60))))

print( results.collect() )
# [(685, '11:25'), (180, '03:00'), (80, '01:20')]