Datetime
From charlesreid1
Dealing with date and time stamps in CSV files for populating an SQL database, all using Python.
The First Question: Dealing With CSV Date/Time Stamps
The First Question: How to deal with date and time stamps from CSV files, and their many varieties?
We will be using Python to handle the date and time stamps.
Dates and Times in Python
You can use the excellent datetime utility to deal with all things dates and times.
Our task is to turn a string, like "2016-02-04 22:09:06", into a datetime object. This object will have an underlying representation, consisting of the year, the month, the day, the hour, the minute, and the second.
To turn a string into a datetime object, use the datetime.strptime() method. Here is a link to the datetime library documentation, about strptime(): https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime
We can call it like so:
test_datetime.py
import datetime
x = "2016-02-04 22:09:06"
x_datetime = datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
If we print out x_datetime, we can see it is a datetime object:
>>> print x_datetime 2016-02-04 22:09:06 >>> print type(x_datetime) <type 'datetime.datetime'> >>>
The Second Question: SQL and Date/Time Stamps
The Second Question: How does SQL deal with date and time stamps? How do you initialize a table with a column for date and time stamps, and how do you create a new record with that information?