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).
Related
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.
I have a python script that generates a datetime string using this line of code:
data['timestamp'] = datetime.isoformat(datetime.utcnow())
That generates something like the following:
2017-05-24T04:08:09.530033
How do I convert that to "MYSQL insertable" datetime format in a clean way?
Thanks!
Try to use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert.
I hope this may help you
You can specify any type of format like this depending on the one you `ve set in mysql
data['timestamp'] =pd.to_datetime(data['timestamp'] , format='%d%b%Y:%H:%M:%S.%f')
First off, it looks like you ran from datetime import * rather than import datetime. That's tempting because it lets you type less when you want to refer to parts of the module, but it can get you into name collision issues later. An alternative with less typing is something like import datetime as dt, that way later you can just use dt.datetime. This will make your code cleaner.
MySQL accepts several date formats, which can be read about in detail here. In particular:
The DATETIME type is used for values that contain both date and time
parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format.
ISO8601 numbers look just like that! 2017-05-24T04:19:32
So if the only difference is the "T" in the middle instead of a space, just run something like this, assuming you don't change your import statements.
timestamp = str(datetime.isoformat(datetime.utcnow()))
timestamp = timestamp.replace("T", " ")
data['timestamp'] = timestamp
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.
How to set default datetime format in python because i have multiple tuples to send via template on client side. This is not good approach to set each object's value to specified format. I want to set a datetime format on server side and these converted values will be shown to client. I tried
datetime.strftime("%Y-%m-%d %X")
but it is giving error.
strftime is a method of datetime objects - it doesn't set a default representation, which seems to be what you suggest. For example, you might call it like this:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%Y-%m-%d %X")
'2011-03-17 10:14:12'
If you need to do this a lot, it would be worth creating a method that wraps this conversion of a datetime to a string. The documentation for the datetime module can be found here.
I'm not sure I understand your issue, but this might help
http://docs.djangoproject.com/en/dev/ref/settings/
there is a datetime format section, this sets datetime format globally.
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.