简体   繁体   中英

How to infer type from datetime string in Python

I have a table for which I want to infer custom types for each column. Given a string, I want to distinguish whether it is a date, a time or a timestamp. For instance, for the given list:

input_list = [
    "4th Sep 2013",
    "95-04-04 23:33:05",
    "May 5th 1999",
    "03:00:00",
    "10-01-22",
    "12-12-25 05:48:01.0010"]

I want an output that tells me (a list of strings)

output_types = [
    "date",
    "timestamp",
    "date",
    "time",
    "date",
    "timestamp"]

I have tried using datetime , but since I can't be sure of the input format (especially for dates) it is hard to infer automatically the input type.

The parsedatetime module seems to provide this functionality, in the parsedatetime.Calendar.parse() method. According to the documentation:

If the datetimeString is parsed and date/time value found then the second item of the returned tuple will be a flag to let you know what kind of struct_time value is being returned:

 0 = not parsed at all 1 = parsed as a date 2 = parsed as a time 3 = parsed as a datetime 

I don't know if it supports every date/time format that you've given in the examples.

Python supports posix from an OS level. You can use posix to distinguish between the different string types.

You can find more relevant details here : https://docs.python.org/2/library/posix.html

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