convert datetime string to datetime - python

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.

Related

Float to datetime returns wrong output (Same Month) - Python

I have a column of float values which are tweet creation dates. This is the code I used to convert them from float to datetime:
t = 1508054212.0
datetime.utcfromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
All the values returned belong to October 2017. However, the data is supposed to be collected over multiple months. So the dates should have different months and not just different Hours, Minutes and Seconds.
These are some values which I need to convert:
1508054212.0
1508038548.0
1506890436.0
Request you to suggest an alternative approach to determine the dates. Thank you.
I assumed df['tweet_creation'].loc[1] will return a number like the examples you gave.
Unfortunately, I don't know what f is, but I assumed it was a float.
My answer is inspired by this other answer: Converting unix timestamp string to readable date. You have a UNIX timestamp, so the easiest way is to use it and not convert it as a string.
from datetime import datetime, timedelta
dtobj = datetime.utcfromtimestamp(int(df['tweet_creation'].loc[1])) + timedelta(days=f-int(f))
To have the string representation you can use the function strftime.

Is there a way to convert datetime to acceptable format?

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')

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).

How do I convert the output of "getctime()" and "getmtime()" into the time format required by HTML's "published_time" and "modified_time" META tags?

My website's articles are written using .md files, to get the created and modified times of these files I use the os.path.getctime() and os.path.getmtime() methods.
The output of these methods look like this:
1553541590.723329
1553541590.723329
While HTML requires this format:
2001-09-17T05:59:00+01:00
2013-09-16T19:08:47+01:00
I have two questions regarding this matter:
What's are the names of these two time formats?
How do I change the output of those methods to look like the required HTML format?
Thanks.
1) The os.path documentation indicates that both os.path.getctime() and os.path.getmtime() return a float indicating seconds since epoch. That seems consistent with the numbers you are getting.
2) The easiest thing to do would be to convert to an object to represent a date and then provide your desired format. Here, I used datetime with strftime() to output a string of desired format.
import datetime
>>>> datetime.datetime.fromtimestamp(1553541590.723329)
datetime.datetime(2019, 3, 25, 12, 19, 50, 723329)
>>>> datetime.datetime.fromtimestamp(1553541590.723329).strftime('%Y-%m-%dT%H:%M:%S')
'2019-03-25T12:19:50'
You may find it easiest to just add the time zone string on the end since adding a timezone to a datetime object is a little involved. If you do want to go through with it, you need to create a tzinfo object and use it to update the datetime object using datetime.astimezone(tz). Here's a pretty good resource for adding a timezone to a datetime object.

How do I get my Python date in the format that I want?

I'm reading a date from an Excel cell in Python (using .Value on the cell)... the result that I get is:
07/06/10 00:00:00
I thought this was a string, and so went about trying to figure out how to convert this to the format I need ("yyyyMMdd", or "20100706" in this example). However, after some playing around I realized that it is not being pulled as a string... Running type() on it returns <type 'time'> .
I then assumed that it was a Python time object, and tried using strftime on it to convert it to a string... but that didn't work either. It doesn't recognize the strftime method on the value.
Any idea on how to parse this properly and get the format I want? What am I doing wrong? (And if this clearly contains a date as well as a time, why is Python automatically considering it a time object?)
You can convert it to a time object like this:
import time
time.strptime(str(thetime), '%m/%d/%y %H:%M:%S')
And then you should be able to manipulate it to your hearts content.
HTH
Have you tried str(time)? That should give it to you in a string and then you can play around with the formatting all you like.

Categories

Resources