0

I want my users to input date as a string.

The date is passed via a Python backend to a MySQL database where it is stored as datetime.

What is a way of doing this? To clarify, I am asking what kinds of conversions I should do, where, and using what packages.

MarianD
  • 13,096
  • 12
  • 42
  • 54
user1283776
  • 19,640
  • 49
  • 136
  • 276
  • How do you pass data to your server? – Sushant Sep 07 '18 at 12:15
  • If timezones are in play, get the time zone from either user input or preferably [client-side javascript](https://stackoverflow.com/questions/1091372/getting-the-clients-timezone-in-javascript), then on your server convert the datetime to UTC before storing it. When you retrieve it you always have UTC so it's fairly simple to convert that to either the server timezone or the user's timezone. – James Sep 07 '18 at 12:31
  • @ThatBird I pass data by graphQL. The client uses the apollo library and the server uses the graphene library. – user1283776 Sep 07 '18 at 12:47
  • @James: time zones definitely are something I should be considering. Yes, I want the time to be stored as UTC. – user1283776 Sep 07 '18 at 12:48

1 Answers1

1

Now a lot of things in this domain depends on your use-case but I'll take a shot. I'm guessing you pass your data to the server after JSON.stringifying it?

Now we have data on the server. You get everything as json strings, do a json loads and convert them to python strings(unicodes) on your server. From here on, things are easy except for one single problem

You'll have to know the format of your date beforehand

Why?

Because you'll have to do a strptime on your date. A simple example of converting a string date to datetime object is -

from datetime import datetime
dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") 
# strptime("date string", "format of date")

The example can be found just below this.

The format table can be found here (which is quite handy, I'd bookmark it)

I hope that makes some if not complete sense

Sushant
  • 3,499
  • 3
  • 17
  • 34
  • Thanks for giving it a good shot! How about time zones? I answered your comment above if that is of any additional help. – user1283776 Sep 07 '18 at 12:49
  • 1
    @user1283776 you can use [Date.UTC()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) in javascript to get UTC time, and in python [utcfromtimestamp()](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcfromtimestamp) – Sushant Sep 07 '18 at 13:28