简体   繁体   中英

TensorFlow: How convert tf.Tensor string to python datetime datatype?

In TensorFlow, trying to split date value read from file which is converted to Tensor string type by dataset api. I want to convert this Tensor string datatype to python datetime type so that I can find day of week, hour, day, etc..

This is a very minimal example. You could refactor it for your own purposes.

import tensorflow as tf
from datetime import datetime


sess = tf.Session()

#Should be shortened
def convert_to_date(text):
    date = datetime.strptime(text.decode('ascii'), '%b %d %Y %I:%M%p')
    return date.strftime('%b %d %Y %I:%M%p') 

filenames = ["C:/Machine Learning/text.txt"]

dataset = tf.data.Dataset.from_tensor_slices(filenames)

tf.data.TextLineDataset
dataset = dataset.flat_map(
                   lambda filename :
                   tf.data.TextLineDataset( filename ) ).map( lambda text :
                                                                        tf.py_func(convert_to_date,
                                                                                  [text],
                                                                                  [tf.string]))
iterator = dataset.make_one_shot_iterator()
date = iterator.get_next()


print(sess.run([date]))

Output is

[(b'Jun 01 2005 01:33PM',)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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