Saturday, July 7

Datetime in python

I have constantly used the Datetime module in python during programming, especially in projects with database. Here I summarize some basics just for reference, because sometimes I find official python doc, while well-written, drills too much on details, which is a good thing for doc, but not for peoples who just want to get some basics and make them work.

Here we only care about two objects in this module, datetime and timedelta. Generally, we think datetime as a way to generate both date and time, like "1988 08 01 16:00", and all we (at least I) need to know about timedelta is we could use it for datetime calculation. There is also a date object that only involving date, "1988 08 11".

Before we create any time objects, let's learn some terms. UTC, stands for Coordinated Universal Time, generally the very primary time standard. Different countries in the world have different time, thought, that is because they are in different time zones. Their time is derived from the time zone offset and UTC; like in NJ, it is "UTC-4". Servers and applications using Internet tend to use UTC to store time-related data to achieve consistency.

There are several ways to create a datetime object.

now() and today() are basically the same, both generate a datetime object based on current local time, but now() has some optional arguments to make it more precise than today(), which could be found in official doc. utcnow() returns the UTC time in the same format of datetime. The last one, strptime() is to generate a datetime format object from a string. To do this you have to specific the format of the string. There is also a another method strftime() to generate a string based on a datetime object.

You could also convert the datetime object into a tuple in struct_time format of time module line 10. This is useful when you want to extract some of the time elements from a datetime object. Above are basically all I need for my small projects without any consideration on time zone stuff.

Now there is another interesting object, timedelta. I find this when I tackle a problem involving shifting time in a calendar. For example, today is July 7th, I want to shift it based on different offsets I give to it. This will cause a lot of problem if you have to design the shift rule, considering months have different number of days. However, use a timedelta object we could shift datetime object just like doing calculations:

The first line is to convert datetime object into date object since we only care about shifting days. Other parts are self-explanatory. You can also set other offset in the timedelta, including seconds, minutes, years, etc.

Finally, here is simple time parser in Java, just for reference:

I use the SimpleDateFormat class to make a time format, set time zone, then parse the long input. Including this is just because my projects involve both python and java.

No comments:

Post a Comment