Date Time split in python

前端 未结 5 1580
再見小時候
再見小時候 2021-02-07 22:58

I have to split a date time which I get from a software in the below format to separate variables (year,month,day,hour, min,sec)

19 Nov 2015  18:45:00.000


        
相关标签:
5条回答
  • 2021-02-07 23:31

    First pip install python-dateutil then do:

    >>> from dateutil.parser import parse
    >>> dt = parse('19 Nov 2015  18:45:00.000')
    >>> dt.year
    2015
    >>> dt.month
    11
    >>> dt.day
    19
    >>> dt.hour
    18
    >>> dt.minute
    45
    >>> dt.second
    0
    
    0 讨论(0)
  • 2021-02-07 23:33

    Below solution should work for you:

    import datetime
    
    string = "19 Nov 2015  18:45:00.000"
    date = datetime.datetime.strptime(string, "%d %b %Y  %H:%M:%S.%f")
    
    print date
    

    Output would be:

    2015-11-19 18:45:00
    

    And you can access the desired values with:

    >>> date.year
    2015
    >>> date.month
    11
    >>> date.day
    19
    >>> date.hour
    18
    >>> date.minute
    45
    >>> date.second
    0
    

    You can check datetime's package documentation under section 8.1.7 for srtptime function's usage.

    0 讨论(0)
  • 2021-02-07 23:33
    df2['invoice_date']=pd.to_datetime(df2.invoice_date, format='%m/%d/%Y %H:%M')
    
    
    df2.insert(loc=5, column='month', value=df2.invoice_date.dt.month)
    # +1 to make Monday=1.....until Sunday=7
        df2.insert(loc=6, column='day', value=(df2.invoice_date.dt.dayofweek)+1)
        df2.insert(loc=7, column='hour', value=df2.invoice_date.dt.hour)
    
    0 讨论(0)
  • 2021-02-07 23:35

    As an alternative to wim's answer, if you don't want to install a package, you can do it like so:

    import datetime
    
    s = "19 Nov 2015  18:45:00.000"
    d = datetime.datetime.strptime(s, "%d %b %Y  %H:%M:%S.%f")
    
    print d.year
    print d.month
    print d.day
    print d.hour
    print d.minute
    print d.second
    

    This outputs:

    2015
    11
    19
    18
    45
    0
    

    This utilizes strptime to parse the string.

    0 讨论(0)
  • 2021-02-07 23:41

    Use datetime.strptime(your_string, format)

    To contsruct the format string, consult the documentation: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

    From there, you can easily get the year, month, etc. (also in the documentation)

    0 讨论(0)
提交回复
热议问题