Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Creating a Date-Time

There are two use cases for creating date, time, struct_time or datetime instances. In the simplest case, we're asking our operating system for the current date-time or the date-time associated with some resource or event. In the more complex case, we are asking a user for input (perhaps on an interactive GUI, a web form, or reading a file prepared by a person); we are parsing some user-supplied values to see if they are a valid date-time and using that value.

From The OS. We often get time from the OS when we want the current time, or we want one of the timestamps associated with a system resource like a file or directory. Here's a sampling of techniques for getting a date-time.

time.time() → float

Returns the current moment in time as a float seconds number. See Chapter 33, File Handling Modules for examples of getting file timestamps; these are always a float seconds value. We'll often need to convert this to a struct_time or datetime object so that we can provide formatted output for users.

The functions time.localtime or time.gmtime will convert this value to a struct_time. The class methods datetime.datetime.fromtimestamp, and datetime.datetime.utcfromtimestamp will create a datetime object from this time value.

Then, we can use time.strftime or time.asctime to format and display the time.

time.ctime() → string, time.asctime() → string

Returns a string representation of the current time. These values aren't terribly useful for further calculation, but they are handy, standardized timestamp strings.

time.localtime() → struct_time, time.gmtime() → struct_time

When these functions are evaluated with no argument value, they will create struct_time objects from the current time. Since we can't do arithmetic with these values, we often need to convert them to something more useful.

The time.mktime function will convert the struct_time to a float seconds time.

We have to use the datetime.datetime constructor to create a datetime from a struct_time. This can be long-winded, it will look like datetime.date( ts.tm_year, ts.tm_month, ts.tm_day ).

datetime.datetime.today() → datetime, datetime.datetime.now() → datetime, datetime.datetime.utcnow() → datetime

All of these are class methods of the datetime class; the create a datetime object. The today function uses the simple time.time() notion of the current moment and returns local time. The now function may use a higher-precision time, but it will be local time. The utcnow function uses high-precision time, and returns UTC time, not local time.

We can't directly get a float seconds number number from a datetime value. However, we can do arithmetic directly with datetime values, making the float seconds value superflous.

We can get the struct_time value from a datetime, using the timetuple or utctimetuple method functions of the datetime object.

Getting Time From A User. Human-readable time information generally has to be parsed from one or more string values. Human-readable time can include any of the endless variety of formats in common use. This will include some combination of years, days, months, hours, minutes and seconds, and timezone names.

There are two general approaches to parsing time. In most cases, it is simplest to use datetime.strptime to parse a string and create a datetime object. In other cases, we can use time.strptime. In the most extreme case, we have to either use the re module (xChapter 31, Complex Strings: the re Module ), or some other string manipulation, and then create the date-time object directly.

datetime.strptime( string , 〈 format 〉) → datetime

This function will use the given format to attempt to parse the input string. If the value doesn't match the format, it will raise a ValueError exception. If the format is not a complete datetime, then defaults are filled in. The default year is 1900, the default month is 1 the default day is 1. The default time values are all zero.

We'll look at the format string under the time.strftime function, below.

time.strptime( string , 〈 format 〉) → struct_time

This function will use the given format to attempt to parse the input string. If the value doesn't match the format, it will raise a ValueError exception. If the format is not a complete time, then defaults are filled in. The default year is 1900, the default month is 1 the default day is 1. The default time values are all zero.

We'll look at the format string under the time.strftime function, below.

time.struct_time( 9-tuple ) → struct_time

Creates a struct_time from a 9-valued tuple: ( year, month, day, hour, minute, second, day of week, day of year, dst-flag ). Generally, you can supply 0 for day of week and day of year. The dst flag is 0 for standard time, 1 for daylight (or summer) time, and -1 when the date itself will define if the time is standard or daylight.

This constructor does no validation; it will tolerate invalid values. If we use the time.mktime function to do a conversion, this may raise an OverflowError if the time value is invalid.

Typically, you'll build this 9-tuple from user-supplied inputs. We could parse a string using the re module, or we could be collecting input from fields in a GUI or the values entered in a web-based form. Then you attempt a time.mktime conversion to see if it is valid.

datetime.datetime( year , month , day , hour , 〈 minute second microsecond 〉〈 tzinfo 〉) → datetime

Creates a datetime from individual parameter values. Note that the time fields are optional; if omitted the time value is 0:00:00, which is midnight.

This constructor will not tolerate a bad date. It will raise a ValueError for an invalid date.


 
 
  Published under the terms of the Open Publication License Design by Interspire