Is there a way to convert datetime to acceptable format? - python

I have a program that predicts stock market with ETNA (Tinkoff's repository)
train_ts, test_ts = ts.train_test_split(train_start='2021-05-30',
train_end='2022-04-30',
test_start='2022-05-08',
test_end='2022-05-30')
I am trying to actualise programm for each day by using
'today = datetime.today()'
but when i have an error
TypeError: cannot do slice indexing on DatetimeIndex with these indexers [today] of type str
how to convert "today" to an acceptable format?
Maybe you can suggest better ways to do what i want. As i undersatnd i can't use today with strptime

Use datetime.strftime() to convert a datetime object to a formatted string.
This particular function will convert a datetime object into a string matching the format specified in your example (and the ETNA docs).
dt_object.strftime('%Y-%m-%d')

Related

Pandas: Change object to Date_time

I'm learning Pandas and I have a problem trying to change a format from Object to Date_time.
When I use 'to_datetime' the date I get in return is like in ISO Format, and I just want DD/MM/YYYY (13/10/1960). And I doing something wrong? Thanks a lot!!
enter image description here
At a glance, it doesn't seem like the code uses the right format.
The to_datetime() with the format argument follows strftime standards per the documentation here, and it's a way to tell the method how the original time was represented (so it can properly format it into a datetime object). An example can be seen from this Stack Overflow question.
Simple example:
datetime_object = pd.to_datetime(format='%d/%m/%Y')
The next problem is how you want that datetime object to be printed out (i.e. DD/MM/YYYY). Just throwing thoughts out there (would comment, but I don't have those privileges yet), if you want to print the string, you can cast that datetime object into the string that you want. Many ways to do this, one of which is to use strftime().
Simple example:
date_as_string = datetime_object.strftime('%d/%m/%Y')
But of course, why would you use a datetime object in that case. So the other option I can think of is to override how the datetime object is printed (redefining __str__ in a new class of datetime).

Python datetime without Y-M-D

I'm converting an string type of Time series to datetime in Python and I'm so confused that why is my datetime always display the result I don't expect. \n
what I want is shown in my img here
import datetime
time = '23:30:00' # Time in string format
dt=datetime.datetime.strptime(time, '%H:%M:%S')
print(dt.time()) # time method will only return the time
I hope this helps
You should put your question in the question, not some off-site illustration. We do have code blocks available. Also, you converted to Pandas datetime, not Python datetime. Both of these have "date" in their name because they do contain the date. You could represent just a time using e.g. Pandas timedelta or Python datetime.time. The format you pass to panads.to_datetime is how to parse the input, not how to display the result.
You have converted your string Series to a Series of pd.Timestamp. Internally a Timestamp is a number of nanoseconds from 1970-01-01 00:00:00.
The correct way to format a date in pandas is to convert it to a string with .dt.strfime, *when you no longer need to process it as a Timestamp.
TL/DR:
if you want it in HH:MM:SS format leave it in string dtype
if you need to process it as a Timestampand yet have it in HH:MM:SS format, convert it to Timestamp, process it and when done convert it back to a string

How to convert hhmmss.ff format into datetime with pandas

How can I convert the following time format:
hhmmss.ff (like 110241.22 is 11:02:41.22)
into the date/time format with pandas?
I tries to use pandas.to_datetime() but it fails to do the conversion. Here is an example:
hhmmss='110241.22'
pd.to_datetime(hhmmss)
Thanks
You need to specify the format you want to convert the time to. Here's a helpful resource for figuring out what each symbol means. Here's Pandas documentation
pd.to_datetime(df['column_name'], format = '%H%M%S.%f')

Checking if a python variable is a date?

One thing that I'm finding hard with the pandas/numpy combo is dealing with dates. My dataframe time series indices are often DateTimeIndexes containing Timestamps but sometimes seem to be something else (e.g. datetime.Date or numpy.datetime64).
Is there a generic way to check if a particular object is a date, i.e. any of the known date variable types? Or is that a function I should look to create myself?
Thanks!
I use this function to convert a series to a consistent datetime object in pandas / numpy. It works with both scalars and series.
import pandas as pd
x = '2018-12-11'
pd.to_datetime(x) # Timestamp('2018-12-11 00:00:00')
if isinstance(yourVariable,datetime.datetime):
print("it's a date")
I would try converting the string representation of what I suspect to be a datetime into a datetime object, using the parse function from dateutil.parser.
https://chrisalbon.com/python/basics/strings_to_datetime/

convert datetime string to datetime

I know questions like these get asked all the time, but my specific problem doesn't seem to come up (at least I can't find it).
So my problem is like this. I have a MySQL database which has lots of data in it, with one column being full of dates. When I pull these dates, I automatically store them into a list which works great.
But, I also have to format the dates to calculate with. For instance, if I work on one of the dates I may need to extract just the month number. Having imported datetime, I would have imagined it was simple with strftime, but it wasn't. The problem is that they are stored in a string format (list is called last_shipped).
The dates come into the list according to this format:
((datetime.datetime(2012, 11, 30, 0, 0),),)
So when I try and use strftime I get the error
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
My question is, how do I convert a list full of these to a list of workable datetime objects?
Thanks in advance
EDIT:
I am using MySQLdb.
An example of the code I have tried that produces the error above is:
z = datetime.datetime.strftime(gr, '%m')
In this case z is the datetime string I mentioned above.
This will help you:
time.strptime(string[, format])
Parse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().
time.strftime(format[, t])
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.

Categories

Resources