繁体   English   中英

如何从日期时间字符串中检索年,月,日,小时和分钟?

[英]How do I retrieve the year, month, day, hours and minutes from date-time string?

我试图从张量字符串"2018/12/31 22:59"提取年,月,日,小时和分钟的值。 我为此任务找到了此函数tf.string_split ,但是我的代码抛出了错误

Traceback (most recent call last):
  File "path/to/my/file.py", line 12, in <module>
    date = split_date_time[0]
TypeError: 'SparseTensor' object does not support indexing

这是代码

import tensorflow as tf

date_time = tf.placeholder(dtype=tf.string)

day = tf.placeholder(shape=[None], dtype=tf.int32),
month = tf.placeholder(shape=[None], dtype=tf.int32),
year = tf.placeholder(shape=[None], dtype=tf.int32),
hour = tf.placeholder(shape=[None], dtype=tf.int32),
minute = tf.placeholder(shape=[None], dtype=tf.int32)

split_date_time = tf.string_split(date_time, ' ')
date = split_date_time[0]
time = split_date_time[1]

date_splitted = tf.string_split(date, '-')
year = date_splitted[0]
month = date_splitted[1]
day = date_splitted[2]

time_spplitted = tf.string_split(time, ':')
hour = time_spplitted[0]
minute = time_spplitted[1]

with tf.Session() as sess:
    print (sess.run(year, feed_dict={date_time: "2018-12-31 22:59"}))
    print (sess.run(month, feed_dict={date_time: "2018-12-31 22:59"}))
    print (sess.run(day, feed_dict={date_time: "2018-12-31 22:59"}))
    print (sess.run(hour, feed_dict={date_time: "2018-12-31 22:59"}))
    print (sess.run(minute, feed_dict={date_time: "2018-12-31 22:59"}))

您的代码中有几个问题(主要是因为您显然没有阅读任何有关要使用的功能的文档)。 我将仅提及与您要解决的特定问题相关的一些关键问题(但我强烈建议您学习TensorFlow的基础知识及其计算模型)。

首先,作为的文档tf.string_split状态的第一个参数tf.string_split应该是“1-d串张量,字符串分割 ”。 但是, "2018-12-31 22:59"是一个0-D字符串张量。

其次, tf.string_split返回一个tf.SparseTensor ,该索引无法索引!

这是您问题的可能解决方案:

import tensorflow as tf

date_time = tf.placeholder(shape=(1,), dtype=tf.string)

split_date_time = tf.string_split(date_time, ' ')

date = split_date_time.values[0]
time = split_date_time.values[1]

split_date = tf.string_split([date], '-')
split_time = tf.string_split([time], ':')

year = split_date.values[0]
month = split_date.values[1]
day = split_date.values[2]

hours = split_time.values[0]
minutes = split_time.values[1]

with tf.Session() as sess:
    year, month, day, hours, minutes = sess.run([year, month, day, hours, minutes],
                                                feed_dict={date_time: ["2018-12-31 22:59"]})
    print("Year =", year)
    print("Month =", month)
    print("Day =", day)
    print("Hours =", hours)
    print("Minutes =", minutes)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM