Python: serializing/deserializing datetime.time - python

I have a form with dropdowns full of times, represented with datetime.time objects.
What's the best way to serialize the object? eg:
<option value="${time.serialize()}">${time.isoformat()}</option>
And then deserialize it on the other end? eg:
time = datetime.time.deserialize(request.params['time'])

If you repr a datetime.time object, Python gives you isoformat. As reprs attempt to be serialized versions of their objects, that's a good indication it's the value you should use.
import datetime
timestring = datetime.datetime.now().time().isoformat()
timeobj = datetime.datetime.strptime(timestring, "%H:%M:%S.%f").time()

In Python 3.6 and newer you can use the datetime.time.isoformat function to serialize and in Python 3.7 and newer you can use the datetime.time.fromisoformat function to deserialize. So it would look like this
import datetime
time_string = datetime.datetime.now().time().isoformat()
time_obj = datetime.time.fromisoformat(time_string)
and to do this with a datetime instead of a time, it would look like
import datetime
datetime_string = datetime.datetime.now().isoformat()
datetime_obj = datetime.datetime.fromisoformat(datetime_string)

Related

Python Faker Datetime Generation returns tuple with datetime in it - instead just datetime

for testing purposes i want to compare two datetime objects.
dt1 = fake.date_time() # assumming 2021-03-25 08:56:12
dt1 structure
dt2 = datetime.datetime.strptime('2021-03-25 08:56:12', "%Y-%m-%d %H:%M:%S")
dt2 structure
The comparision fails as i try to compare a datetime object with a tuple which has a datetime object in it.
If I try to just assign the first element of the tuple (dt1) like so:
dt1 = fake.date_time()[0]
I get the follow error:
Error directly assign tuple element
But if i do the following, it works:
dt1 = fake.date_time()
dt1 = dt1[0]
What do I not understand here? :( And why isn't faker directly returning a datetime?
Thank you for any help.
I use python 3.7 and faker 6.6.2.
As I was preparing the whole code to be passed here, I discovered the issue.
I copied this line from a dict definition, and it had the comma at the end...
dt = fake.date_time(),
Obviously then python creates a tuple, I just didn't see this.
If you check the Faker date_time function source code you'll see only a single datetime.datetime object retuns:
def date_time(self, tzinfo=None, end_datetime=None):
"""
Get a datetime object for a date between January 1, 1970 and now
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2005-08-16 20:39:21')
:return datetime
"""
# NOTE: On windows, the lowest value you can get from windows is 86400
# on the first day. Known python issue:
# https://bugs.python.org/issue30684
return datetime(1970, 1, 1, tzinfo=tzinfo) + \
timedelta(seconds=self.unix_time(end_datetime=end_datetime))
I suspect an unwanted change has been applied to the dt1 object (or it can be a debugger bug also), as I can see in the error clearly stated that the datetime.datetime object is not subscriptable . Would you add the complete code for further checking?

Python datetime.today() to handle timezone

Hi apologies on basic python datetime question but I am a little confused:
I want to just have a variable the prints today's date, with consideration to the time zone the program I am running it in. Let's say California.
import datetime
import pytz
utc_now = pytz.utc.localize(datetime.datetime.utcnow())
pst_now = utc_now.astimezone(pytz.timezone("America/Los_Angeles"))
x = pst_now.isoformat()
for x it returns :
2020-01-13T17:43:56.155556-08:00
how can I get it to return:
2020-01-13
I tried:
datetime.datetime.strptime(x, '%Y-%m-%d)
But it did not work
If you're just looking to return the time of the local machine, no need to deal with timezones directly in your code, you can use the now function of datetime.
import datetime
datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
x is a string. pst_now is a datetime object which, when the method .isoformat() is called on it, produces a string.
Solution: call strftime on pst_now:
x = pst_now.strftime('%Y-%m-%d')
You can convert pst_now to a date() object:
pst_now.date().isoformat()
'2020-01-13'

converting between timezones (format same instance in time) in python 3

I have a list of timestamps which look like so:
time_list=['2016-10-01T00:00:00+01:00','2016-10-01T23:00:00+00:00','2016-10-01T22:00:00+02:00',..]
I would like to apply a magic function to this list which gets them all in +00:00 timezone - this should result in (all timestamps should correctly adjusted to the +00:00 format):
ret_list=['2016-10-01T23:00:00+00:00','2016-10-01T23:00:00+00:00','2016-10-01T23:00:00+00:00',..]
You have to convert your isoformat strings to datetime objects first, change timezones to UTC and then stringify back.
If you are on python 3.7, according to this, you can use fromisoformat method of datetime, but if you don't, like me, I think the best option involves the use of dateutil module (you have to install it) and pytz:
import datetime as dt
from dateutil import parser
import pytz
time_list = ['2016-10-01T00:00:00+01:00','2016-10-01T23:00:00+00:00','2016-10-01T22:00:00+02:00']
utc_time_list = [parser.parse(x).astimezone(pytz.utc).isoformat() for x in time_list]
print(utc_time_list)
['2016-09-30T23:00:00+00:00', '2016-10-01T23:00:00+00:00', '2016-10-01T20:00:00+00: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.

Categories

Resources