Google app engine datastore datetime to date in Python? - python

I've always hated the headache of managine dates, times, datetimes, and the various formats and conversions that are needed with them. I'm taking an online course on using the google app engine and it says to use the datetime property, which is returning a date in the format:
2012-06-25 01:17:40.273000
I tried
datetime.strptime('2012-06-25 01:17:40.273000','%y-%m-%d %H:%M:%S')
but it didn't work..
I just want to extract the 2012-06-25 part without using a hacky regex or string slicing solution.
How do I parse this and convert it to the proper format?

Finally found it (shortly after asking the question, but I've been trying for the past hour)
datetime.strptime('2012-06-25 01:17:40.273000','%Y-%m-%d %H:%M:%S.%f')
What I wanted:
datetime.strptime('2012-06-25 01:17:40.273000','%Y-%m-%d %H:%M:%S.%f').strftime('%m-%d-%Y')

If you are using a datetime property then the object you get back is a datetime instance not a string.
On the console
>>> from datetime import datetime
>>> x = datetime.now()
>>> print x
2012-06-25 12:03:15.835467
>>> x.date()
datetime.date(2012, 6, 25)
>>>
>>> print x.date()
2012-06-25
>>>
See the print statement. It does an implicit conversion to string. If your outputting the datetime property value in a template, this is probably what is happening.
So in your code you should just use .date() method on the datetime object.

Related

DateTime String via MySQL DATE_FORMAT or DateTime.strftime

I have a function that consumes a datetime string that is returned from a DB query. Right now the query returns a datetime object.
What I am looking for is what would be the preferred way to create my datetime string. I have not done any performance profiling yet, just looking for previous experiences from people.
It depends.
Normally, the database is just a repository for data; it is not a formatting engine. This implies that you should expect to get strings like "2019-06-24 13:47:24" or numbers like 1561409293 and you deal with them from there.
However, it is often more straightforward to simply call DATE_FORMAT() in your SELECT statement. This is especially handy when the SELECT can generate the entire 'report' without further manipulation.
Another way to decide... Which approach requires fewer keystrokes on your part? Or has the least chance of programming errors? Or...
You say "consumes a datetime string that is returned from a DB query" -- but what will it do with it? If it will be manipulating it in more than one way, then a client "object" sounds like the better approach. If you will simply display the datetime, then DATE_FORMAT() may be better.
There is no noticeable performance difference.
If you have a datetime object, could could just keep it around in your code as a datetime object, extracting whatever information you need from it. Then when you really need the actual string, use strftime to format it in the way you want.
>>> from datetime import datetime
>>> t = datetime.now()
>>> t
datetime.datetime(2019, 6, 24, 14, 23, 45, 835379)
>>> print(t.month)
6
>>> print(t.second)
45
>>> as_string = t.strftime("%B %d, %Y")
>>> print(as_string)
June 24, 2019
>>> as_another_string = t.strftime("%Y-%h-%d %H:%m")
>>> print(as_another_string)
2019-Jun-24 14:06
This page shows you the sorts of format codes you can call upon, in order to extract whichever date/time information you want to display in your string:

Python Convert a Date Time to just Time

I have a field that shows time as 1900-01-01 00:05:00 but I want to show it as just 00:05:00 i.e. just five minutes.
I have been looking at the python documentation and it is driving me crazy. From the question How do I find the time difference between two datetime objects in python? it looks like is should be something do with timedelta but I am not getting any closer to a solution. The question Converting Date/Time to Just Time suggests you can just use a format tag but that is not working for me. I also looked at converting date time to string without success, I know this is something simple but I have looked at hundreds of pages looking for something simple. All help would be appreciated.
Say you have a Datetime object now:
now.time().strftime('%H:%M:%S')
Load the string with strptime() and get the time() component:
>>> from datetime import datetime
>>> s = "1900-01-01 00:05:00"
>>> dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> dt.time().isoformat()
'00:05:00'
Here we are dumping the time with isoformat() in ISO 8601 format, but you can also dump the datetime.time back to string with strftime():
>>> dt.time().strftime("%H:%M:%S")
'00:05:00'

Python DateUtil Converting string to a date and time

I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library
from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt
every time i run this i get
2001-09-01 12:00:03
regardless of whether i have dayfirst set as true or Year first set as false. Ideally I just want to have a date in the format DD-MM-YYYY HH:MM:SS. I don't want anything fancy. I am willing to use the datetime library but this doesn't seem to work at all for me. Can anyone give simple expamples of how to convert strings to date time with an explicit format, I'm a noob, so the most basic examples are all i require. I'm using Python 2.7
The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed.
parser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with
print dt.strftime("%d-%m-%Y %H:%M:%S")
it will work as you expect.
The standard lib (built-in) datetime lib can do this easily.
from datetime import datetime
my_date_string = "2001/9/1 12:00:03"
d = datetime.strptime(my_date_string, "%Y/%m/%d %H:%M:%S")
print d.strftime("%d-%m-%Y %H:%M:%S")

set default datetime format in python

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.

Now to convert this strings to date time object in Python or django?

Now to convert this strings to date time object in Python or django?
2010-08-17T19:00:00Z
2010-08-17T18:30:00Z
2010-08-17T17:05:00Z
2010-08-17T14:30:00Z
2010-08-10T22:20:00Z
2010-08-10T21:20:00Z
2010-08-10T20:25:00Z
2010-08-10T19:30:00Z
2010-08-10T19:00:00Z
2010-08-10T18:30:00Z
2010-08-10T17:30:00Z
2010-08-10T17:05:00Z
2010-08-10T17:05:00Z
2010-08-10T15:30:00Z
2010-08-10T14:30:00Z
whrn i do this datestr=datetime.strptime( datetime, "%Y-%m-%dT%H:%M:%S" )
it tell me that unconverted data remains: Z
You can parse the strings as-is without the need to slice if you don't mind using the handy dateutil module. For e.g.
>>> from dateutil.parser import parse
>>> s = "2010-08-17T19:00:00Z"
>>> parse(s)
datetime.datetime(2010, 8, 17, 19, 0, tzinfo=tzutc())
>>>
Use slicing to remove "Z" before supplying the string for conversion
datestr=datetime.strptime( datetime[:-1], "%Y-%m-%dT%H:%M:%S" )
>>> test = "2010-08-17T19:00:00Z"
>>> test[:-1]
'2010-08-17T19:00:00'
Those seem to be ISO 8601 dates. If your timezone is always the same, just remove the last letter before parsing it with strptime (e.g by slicing).
The Z indicates the timezone, so be sure that you are taking that into account when converting it to a datetime of a different timezone. If the timezone can change in your application, you'll have to parse that information also and change the datetime object accordingly.
You could also use the pyiso8601 module to parse these ISO dates, it will most likely also work with slighty different ISO date formats. If your data may contain different timezones I would suggest to use this module.
change your format string to ""%Y-%m-%dT%H:%M:%SZ" so that it includes the trailing Z (which makes it no longer unconverted). Note, however, that this Z perhaps is there to indicate that the time is in UTC which might be something you need to account for otherwise

Categories

Resources