Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Time split in python

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.

like image 479
Saravana Murthy Avatar asked Nov 19 '15 17:11

Saravana Murthy


People also ask

How do I separate a date and time in a CSV file in Python?

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.

How do I separate a timestamp from a date?

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.


2 Answers

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.

like image 52
Cedric Zoppolo Avatar answered Sep 21 '22 13:09

Cedric Zoppolo


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.

like image 32
Andy Avatar answered Sep 23 '22 13:09

Andy