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
Note : There is two spaces between the date and time. The whole date and time is stored in a single string variable. Please help me in this regards.
Thanks in advance.
How do I separate a date and time in a CSV file in Python? Select Text to Columns and choose Space for the Separated By field. By default, the Tab option will be enabled for the Separated By field, so you'll need to uncheck that after choosing Space.
Get Time Value With Formula. If a cell contains a combined date and time, you can use the INT function to pull the time value into a separate column. Dates are stored as numbers in Excel, with the decimal portion representing the time.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With