How to convert date to datetime
How to convert date to datetime
How to convert a String to DateTime in Python
In this python tutorial, we will discuss Python Converting a string to DateTime. We will also check:
Convert a String to DateTime in Python
Let us see, how to convert a string into datetime in python.
In this example, I have imported a module called datetime.
To get the output we will print((datetime.datetime.now())). You can refer to the below screenshot for the output:
How to convert a string to datetime object in Python
Let us see, how to convert a string into datetime object in python.
To get the output as datetime object print(“Datetime: “, dt_object), to get minute object print(“Minute: “, dt_object.minute), to get hour object print(“Hour: “, dt_object.hour) and, to get second object print(“Second: “, dt_object.second).
You can refer below screenshot for the output:
Convert a string to datetime pandas in Python
Now, we can see how to convert a string to datetime pandas in python.
In this example, I have a module called pandas. Pandas is a library that is used for data science. Here, we will import pandas as pd. The pd.to_datetime(dt) method is used to convert the string datetime into a datetime object using pandas in python.
To get the output as datetime object print(pd.to_datetime(dt)) is used.
You can refer the below screenshot for the output:
Python convert a string to datetime with timezone
Now, we can see how to convert a string to datetime with timezone in python.
In this example, I have imported a module called timezone. datetime.now(timezone(‘UTC’)) is used to get the present time with timezone. The format is assigned as time = “%Y-%m-%d %H:%M:%S%Z%z”. The %z is used to get timezone along with datetime.
To get the output print(‘UTC :’, time) is used. In the below screenshot, we can see the output.
Python convert a string to datetime with milliseconds
Let us see how to convert a string to datetime with milliseconds in python.
In this example, I have imported a module called datetime. The dt = datetime.datetime.now() is used to get the present time. Here, %f is used to get time with milliseconds.
To get the output as datetime with milliseconds print(dt). You can refer to the below screenshot for the output:
Python converting a string to datetime without format
Now we can see, how to convert string to datetime without format in python.
In this example, I have imported a module called a parser. The parser function will parse a string automatically in the dt variable. dateutil module is the extension for the standard datetime module. The datetime string is passed without format.
To get the final result print(dt) is used. Below screenshot shows the output:
Python converting a string to datetime iso format
Here, we can see how to converting a string to datetime iso format in python
In this example, I have imported a module called datetime and used .isoformat to convert present time into iso format.
To get the output in iso format, here I have used print(dt.isoformat()). You can see the below screenshot for output:
Python convert a string to datetime yyyy-mm-dd
Now we can see, how to convert a string to datetime yyyy-mm-dd in python.
To get the output print(dt_object) is used in this example. You can refer to the below screenshot for the output:
Python converting a string to datetime yyyy-mm-dd
How to convert a string to timestamp in Python
Here, we can see how to convert a string into timestamp in Python.
In this example, I have imported a module called datetime and assigned an input string as a date and the strptime string is used to get the time in the format. Timestamp() is a function that returns the time in the form of seconds.
To get the output print(ts) is used. In the below screenshot, you can see the output in which the time is in the form of seconds.
Python converting a string to timestamp
Python converting a string to datetime.date
To get the output print(date) is used. You can refer the below screenshot for the output.
Python converting a string to datetime.date
Python converting a datetime to string
Here, we can see how to convert a datetime to string in python.
In this example, I have imported a module called datetime. The datetime.now() is used to get the present datetime. Here, strftime is a string used to get the time proper format, and “%d” is used to get only a date string.
To get the output as date, I have used print(date). Below screenshot shows the output:
How to convert a string to datetime UTC in Python
Here, we can see how to convert a string to datetime utc format in Python.
To get the output as time in UTC format print(utc_date_time), and it will return date and time. You can refer to the below screenshot for the output.
You may like the following Python tutorials:
In this Python tutorial, we have learned about how to convert a string to DateTime in Python. Also, We covered these below topics:
Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.
Converting Strings to datetime in Python
Introduction
One of the many common problems that we face in software development is handling dates and times. After getting a date-time string from an API, for example, we need to convert it to a human-readable format. Again, if the same API is used in different timezones, the conversion will be different. A good date-time library should convert the time as per the timezone. This is just one of many nuances that need to be handled when dealing with dates and time.
Thankfully, Python comes with the built-in module datetime for dealing with dates and times. As you probably guessed, it comes with various functions for manipulating dates and times. Using this module, we can easily parse any date-time string and convert it to a datetime object.
Converting Strings Using datetime
For example, the following code will print the current date and time:
Running this code will print something similar to this:
When no custom formatting is given, the default string format is used, i.e. the format for «2018-06-29 08:15:27.243860» is in ISO 8601 format (YYYY-MM-DDTHH:MM:SS.mmmmmm). If our input string to create a datetime object is in the same ISO 8601 format, we can easily parse it to a datetime object.
Let’s take a look at the code below:
Running it will print the date, time, and date-time:
In our example, «2018-06-29 08:15:27.243860» is the input string and «%Y-%m-%d %H:%M:%S.%f» is the format of our date string. The returned datetime value is stored in date_time_obj variable. Since this is a datetime object, we can call the date() and time() methods directly on it. As you can see from the output, it prints the ‘date’ and ‘time’ part of the input string.
All of these tokens, except the year, are expected to be zero-padded.
From the following output you can see that the string was successfully parsed since it is being properly printed by the datetime object here:
Here are a few more examples of commonly used time formats and the tokens used for parsing:
You can parse a date-time string of any format using the table mentioned in the strptime documentation.
Dealing with Timezones and datetime
This code will print:
The output of tzinfo is None since it is a naive datetime object. For timezone conversion, a library called pytz is available for Python. You can install it as described in these instructions. Now, let’s use the pytz library to convert the above timestamp to UTC.
+00:00 is the difference between the displayed time and the UTC time. In this example the value of tzinfo happens to be UTC as well, hence the 00:00 offset. In this case, the datetime object is a timezone-aware object.
Similarly, we can convert date-time strings to any other timezone. For example, we can convert the string «2018-06-29 17:08:00.586525+00:00» to «America/New_York» timezone, as shown below:
Converting Timezones
We can convert timezone of a datetime object from one region to another, as shown in the example below:
First, we created one datetime object with the current time and set it as the «America/New_York» timezone. Then using the astimezone() method, we have converted this datetime to «Europe/London» timezone. Both datetime s will print different values like:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
As expected, the date-times are different since they’re about 5 hours apart.
Using Third Party Libraries
Python’s datetime module can convert all different types of strings to a datetime object. But the main problem is that in order to do this you need to create the appropriate formatting code string that strptime can understand. Creating this string takes time and it makes the code harder to read. Instead, we can use other third-party libraries to make it easier.
In some cases these third-party libraries also have better built-in support for manipulating and comparing date-times, and some even have timezones built-in, so you don’t need to include an extra package.
Let’s take a look at few of these libraries in the following sections.
dateutil
The dateutil module is an extension to the datetime module. One advantage is that we don’t need to pass any parsing code to parse a string. For example:
This parse function will parse the string automatically and store it in the datetime variable. Parsing is done automatically. You don’t have to mention any format string. Let’s try to parse different types of strings using dateutil :
You can see that almost any type of string can be parsed easily using the dateutil module.
While this is convenient, recall from earlier that having to predict the format makes the code much slower, so if you’re code requires high performance then this might not be the right approach for your application.
Maya also makes it very easy to parse a string and for changing timezones. Some simple examples are shown here:
For converting the time to a different timezone:
Now isn’t that easy to use? Let’s try out maya with the same set of strings we have used with dateutil :
As you can see, all of the date formats were successfully parsed.
But did you notice the difference? If we are not providing the timezone info then it automatically converts it to UTC. So, it is important to note that we must provide to_timezone and naive parameters if the time is not in UTC.
Arrow
Let’s try this with the same example string we have used for maya :
And here is how you can use arrow to convert timezones using the to method:
As you can see the date-time string is converted to the «America/New_York» region.
Now, let’s again use the same set of strings we have used above:
This code will fail for the date-time strings that have been commented out, which is over half of our examples. The output for other strings will be:
In order to correctly parse the date-time strings that I have commented out, you’ll need to pass the corresponding format tokens to give the library clues as to how to parse it. For example, «MMM» for months name, like «Jan, Feb, Mar» etc. You can check this guide for all available tokens.
Conclusion
In this article we have shown different ways to parse a string to a datetime object in Python. You can either opt for the default Python datetime library or any of the third-party libraries mentioned in this article, among many others.
The main problem with the default datetime package is that we need to specify the parsing code manually for almost all date-time string formats. So, if your string format changes in the future, you will likely have to change your code as well. But many third-party libraries, like the ones mentioned here, handle it automatically.
One more problem we face is dealing with timezones. The best way to handle them is always to store the time in your database as UTC format and then convert it to the user’s local timezone when needed.
These libraries are not only good for parsing strings, but they can be used for a lot of different types of date-time related operations. I’d encourage you to go through the documents to learn the functionalities in detail.
Python Datetime Tutorial: Manipulate Times, Dates, and Time Spans
Dealing with dates and times in Python can be a hassle. Thankfully, there’s a built-in way of making it easier: the Python datetime module.
datetime helps us identify and process time-related elements like dates, hours, minutes, seconds, days of the week, months, years, etc. It offers various services like managing time zones and daylight savings time. It can work with timestamp data. It can extract the day of the week, day of the month, and other date and time formats from strings.
In short, it’s a really powerful way of handling anything date and time related in Python. So let’s get into it!
In this tutorial, we’ll learn about python datetime functions in detail, including:
As you work through this tutorial, we’d encourage you to run the code on your own machine. Alternatively, if you’d like to run code in your browser and learn in an interactive fashion with answer-checking to be sure you’re getting it right, our Python intermediate course has a lesson on datetime in Python that we recommend. You can start learning by signing up for a free user account.
Learn Data Skills
Get that next raise or to switch to a career in data science by learning data skills.
Sign up for a free account and try our interactive courses in Python, R, SQL, and more!
Python datetime Classes
Before jumping into writing code, it’s worth looking at the five main object classes that are used in the datetime module. Depending on what we’re trying to do, we’ll likely need to make use of one or more of these distinct classes:
If those distinctions don’t make sense yet, don’t worry! Let’s dive into datetime and start working with it to better understand how these are applied.
Creating Date Objects
First, let’s take a closer look at a datetime object. Since datetime is both a module and a class within that module, we’ll start by importing the datetime class from the datetime module.
We can see from the results above that datetime_object is indeed a datetime object of the datetime class. This includes the year, month, day, hour, minute, second, and microsecond.
Extract Year and Month from the Date
Now we’ve seen what makes up a datetime object, we can probably guess how date and time objects look, because we know that date objects are just like datetime without the time data, and time objects are just like datetime without the date data.
We can also antipate some problems. For example, in most data sets, date and time information is stored in string format! Also, we may not want all of this date and time data — if we’re doing something like a monthly sales analysis, breaking things down by microsecond isn’t going to be very useful.
To do this, we need to do a few things.
Handling Date and Time Strings with strptime() and strftime()
Of course, strptime() isn’t magic — it can’t turn any string into a date and time, and it will need a little help from us to interpret what it’s seeing! But it’s capable of reading most conventional string formats for date and time data (see the documentation for more details). Let’s give it a date string in YYYY-MM-DD format and see what it can do!
A full list of these patterns is available in the documentation, and we’ll go into these methods in more depth later in this tutorial.
You may also have noticed that a time of 00:00:00 has been added to the date. That’s because we created a datetime object, which must include a date and a time. 00:00:00 is the default time that will be assigned if no time is designated in the string we’re inputting.
Learn Python the Right Way.
Learn Python by writing Python code from day one, right in your browser window. It’s the best way to learn Python — see for yourself with one of our 60+ free lessons.
Getting Day of the Month and Day of the Week from a Date
Wait a minute, that looks a bit odd! The third day of the week should be Wednesday, not Thursday, right?
Let’s take a closer look at that day_name variable using a for loop:
Now we can see that Python starts weeks on Monday and counts from the index 0 rather than starting at 1. So it makes sense that the number 3 is converted to “Thursday” as we saw above.
Getting Hours and Minutes From a Python Datetime Object
Getting Week of the Year from a Datetime Object
Specifically, isocalendar() returns a tuple with ISO year, week number and weekday. The ISO calendar is a widely-used standard calendar based on the Gregorian calendar. You can read about it in more detail at that link, but for our purposes, all we need to know is that it works as a regular calendar, starting each week on Monday.
Note that in the ISO calendar, the week starts counting from 1, so here 5 represents the correct day of the week: Friday.
We can see from the above that this is the 43rd week of the year, but if we wanted to isolate that number, we could do so with indexing just as we might for any other Python list or tuple:
Converting a Date Object into Unix Timestamp and Vice Versa
In programming, it’s not uncommon to encounter time and date data that’s stored as a timestamp, or to want to store your own data in Unix timestamp format.
We can do that using datetime’s built-in timestamp() function, which takes a datetime object as an argument and returns that date and time in timestamp format:
Measuring Time Span with Timedelta Objects
Often, we may want to measure a span of time, or a duration, using Python datetime. We can do this with its built-in timedelta class. A timedelta object represents the amount of time between two dates or times. We can use this to measure time spans, or manipulate dates or times by adding and subtracting from them, etc.
By default a timedelta object has all parameters set to zero. Let’s create a new timedelta object that’s two weeks long and see how that looks:
Let’s create another timedelta duration to get a bit more practice:
Now let’s start doing using timedelta objects together with datetime objects to do some math! Specifically, let’s add a few diffeent time durations to the current time and date to see what date it will be after 15 days, what date it was two weeks ago.
Note that the output of these mathematical operations is still a datetime object.
Learn Data Skills
Get that next raise or to switch to a career in data science by learning data skills.
Sign up for a free account and try our interactive courses in Python, R, SQL, and more!
Find the Difference Between Two Dates and Times
Similar to what we did above, we can also subtract one date from another date to find the timespan between them using datetime.
Because the result of this math is a duration, the object produced when we subtract one date from another will be a timedelta object.
Here, we’ll create two date objects (remeber, these work the same as datetime objects, they just don’t include time data) and subtract one from the other to find the duration:
Above, we used only dates for the sake of clarity, but we can do the same thing with datetime objects to get a more precise measurement that includes hours, minutes, and seconds as well:
Formatting Dates: More on strftime() and strptime()
We touched briefly on strftime() and strptime() earlier, but let’s take a closer look at these methods, as they’re often important for data analysis work in Python.
strptime() is the method we used before, and you’ll recall that it can turn a date and time that’s formatted as a text string into a datetime object, in the following format:
Note that it takes two arguments:
Let’s try converting a different kind of date string this time. This site is a really useful reference for finding the formatting codes needed to help strptime() interpret our string input.
Now let’s do something a bit more advanced to practice everything we’ve learned so far! We’ll start with a date in string format, convert it to a datetime object, and look at a couple different ways of formatting it (dd/mm and mm/dd).
Then, sticking with the mm/dd formatting, we’ll convert it into a Unix timestamp. Then we’ll convert it back into a datetime object, and convert that back into strings using a few different strftime patterns to control the output:
Here’s an image you can save with a cheat sheet for common, useful strptime and strftime patterns:
Let’s get a little more practice using these:
Handling Timezones
Working with dates and times in Pythin can get even more complicated when timezones get involved. Thankfully, the pytz module exists to help us deal with cross-timezone conversions. It also handles the daylight savings time in locations that use that.
We can use the localize function to add a time zone location to a Python datetime object. Then we can use the function astimezone() to convert the existing local time zone into any other time zone we specify (it takes the time zone we want to convert into as an argument).
This module can help make life simpler when working with data sets that include multiple different time zones.
Working with pandas Datetime Objects
Data scientists love pandas for many reasons. One of them is that it contains extensive capabilities and features for working with time series data. Much like datetime itself, pandas has both datetime and timedelta objects for specifying dates and times and durations, respectively.
We can convert date, time, and duration text strings into pandas Datetime objects using these functions:
And as we’ll see, these functions are actually quite good at converting strings to Python datetime objects by detecting their format automatically, without needing us to define it using strftime patterns.
Let’s look at a quick example:
Note that even though we gave it a string with some complicating factors like a “th” and “sep” rather than “Sep.” or “September”, pandas was able to correctly parse the string and return a formatted date.
We can also use pandas (and some of its affiliated numpy functionality) to create date ranges automatically as pandas Series. Below, for example, we create a series of twelve dates starting from the day we defined above. Then we create a different series of dates starting from a predefined date using pd.date_range() :
Get Year, Month, Day, Hour, Minute in pandas
We can easily get year, month, day, hour, or minute from dates in a column of a pandas dataframe using dt attributes for all columns. For example, we can use df[‘date’].dt.year to extract only the year from a pandas column that includes the full date.
To explore this, let’s make a quick DataFrame using one of the Series we created above:
date | |
---|---|
0 | 2019-08-10 |
1 | 2019-08-11 |
2 | 2019-08-12 |
3 | 2019-08-13 |
4 | 2019-08-14 |
Now, let’s create separate columns for each element of the date by using the relevant Python datetime (accessed with dt ) attributes:
date | year | month | day | hour | minute | |
---|---|---|---|---|---|---|
0 | 2019-08-10 | 2019 | 8 | 10 | 0 | 0 |
1 | 2019-08-11 | 2019 | 8 | 11 | 0 | 0 |
2 | 2019-08-12 | 2019 | 8 | 12 | 0 | 0 |
3 | 2019-08-13 | 2019 | 8 | 13 | 0 | 0 |
4 | 2019-08-14 | 2019 | 8 | 14 | 0 | 0 |
Get Weekday and Day of Year
Pandas is also capable of getting other elements, like the day of the week and the day of the year, from its datetime objects. Again, we can use dt attributes to do this. Note that here, as in Python generally, the week starts on Monday at index 0, so day of the week 5 is Saturday.
date | year | month | day | hour | minute | weekday | day_name | dayofyear | |
---|---|---|---|---|---|---|---|---|---|
0 | 2019-08-10 | 2019 | 8 | 10 | 0 | 0 | 5 | Saturday | 222 |
1 | 2019-08-11 | 2019 | 8 | 11 | 0 | 0 | 6 | Sunday | 223 |
2 | 2019-08-12 | 2019 | 8 | 12 | 0 | 0 | 0 | Monday | 224 |
3 | 2019-08-13 | 2019 | 8 | 13 | 0 | 0 | 1 | Tuesday | 225 |
4 | 2019-08-14 | 2019 | 8 | 14 | 0 | 0 | 2 | Wednesday | 226 |
Convert Date Object into DataFrame Index
We can also use pandas to make a datetime column into the index of our DataFrame. This can be very helpful for tasks like exploratory data visualization, because matplotlib will recognize that the DataFrame index is a time series and plot the data accordingly.
To do this, all we have to do is redefine df.index :
date | year | month | day | hour | minute | weekday | day_name | dayofyear | |
---|---|---|---|---|---|---|---|---|---|
date | |||||||||
2019-08-10 | 2019-08-10 | 2019 | 8 | 10 | 0 | 0 | 5 | Saturday | 222 |
2019-08-11 | 2019-08-11 | 2019 | 8 | 11 | 0 | 0 | 6 | Sunday | 223 |
2019-08-12 | 2019-08-12 | 2019 | 8 | 12 | 0 | 0 | 0 | Monday | 224 |
2019-08-13 | 2019-08-13 | 2019 | 8 | 13 | 0 | 0 | 1 | Tuesday | 225 |
2019-08-14 | 2019-08-14 | 2019 | 8 | 14 | 0 | 0 | 2 | Wednesday | 226 |
Conclusion
In this tutorial, we’ve taken a deep dive into Python datetime, and also done some work with pandas and the calendar module. We’ve covered a lot, but remember: the best way to learn something is by actually writing code yourself!
If you’d like to practice writing datetime code with interactive answer-checking, check out our Python intermediate course for a lesson on datetime in Python with interactive answer-checking and in-browser code-running.
Could you benefit from building new skills?
Pick a skill below and click to sign up for free and start learning instantly!
Date Time. Parse Method
Definition
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Converts the string representation of a date and time to its DateTime equivalent.
Overloads
Converts the string representation of a date and time to its DateTime equivalent by using the conventions of the current culture.
Parses a span of characters into a value.
Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.
Converts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.
Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.
Examples
Numerous examples that call the DateTime.Parse method are interspersed throughout the Remarks section of this article and in the documentation for the individual DateTime.Parse overloads.
Some C# examples in this article run in the Try.NET inline code runner and playground. Select the Run button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.
The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. This may affect the behavior and the output of examples that illustrate the DateTime, DateTimeOffset, and TimeZoneInfo types and their members.
Remarks
In this section:
Which method do I call?
To | Call |
---|---|
Parse a date and time string by using the conventions of the current culture. | Parse(String) overload |
Parse a date and time string by using the conventions of a specific culture. | Parse(String, IFormatProvider) overload (see Parsing and Cultural Conventions) |
Parse a date and time string with special style elements (such as white space or no white space). | Parse(String, IFormatProvider, DateTimeStyles) overload |
Parse a date and time string that must be in a particular format. | DateTime.ParseExact or DateTime.TryParseExact |
Parse a date and time string and perform a conversion to UTC or local time. | Parse(String, IFormatProvider, DateTimeStyles) overload |
Parse a date and time string without handling exceptions. | DateTime.TryParse method |
Restore (round-trip) a date and time value created by a formatting operation. | Pass the «o» or «r» standard format string to the ToString(String) method, and call the Parse(String, IFormatProvider, DateTimeStyles) overload with DateTimeStyles.RoundtripKind |
Parse a date and time string in a fixed format across machine (and possibly cultural) boundaries. | DateTime.ParseExact or DateTime.TryParseExact method |
The string to parse
The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.
The string to be parsed can take any of the following forms:
A string with a date and a time component.
A string with a date but no time component. If the time component is absent, the method assumes 12:00 midnight. If the date component has a two-digit year, it is converted to a year based on the Calendar.TwoDigitYearMax of the current culture’s current calendar or the specified culture’s current calendar (if you use an overload with a non-null provider argument).
A string with a date component that includes only the month and the year but no day component. The method assumes the first day of the month.
A string with a date component that includes only the month and the day but no year component. The method assumes the current year.
A string with a time but no date component. The method assumes the current date unless you call the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles argument, in which case the method assumes a date of January 1, 0001.
A string with a time component that includes only the hour and an AM/PM designator, with no date component. The method assumes the current date and a time with no minutes and no seconds. You can change this behavior by calling the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles argument, in which case the method assumes a date of January 1, 0001.
A string that includes time zone information and conforms to ISO 8601. In the following examples, the first string designates Coordinated Universal Time (UTC), and the second designates the time in a time zone that’s seven hours earlier than UTC:
A string that includes the GMT designator and conforms to the RFC 1123 time format; for example:
«Sat, 01 Nov 2008 19:35:00 GMT»
A string that includes the date and time along with time zone offset information; for example:
The following example parses strings in each of these formats by using the formatting conventions of the current culture, which in this case is the en-US culture:
If the input string represents a leap day in a leap year in the calendar used by the parsing method (see Parsing and cultural conventions), the Parse method parses the string successfully. If the input string represents a leap day in a non-leap year, the method throws a FormatException.
Because the Parse method tries to parse the string representation of a date and time by using the formatting rules of the current or a specified culture, trying to parse a string across different cultures can fail. To parse a specific date and time format across different locales, use one of the overloads of the DateTime.ParseExact method and provide a format specifier.
Parsing and cultural conventions
All overloads of the Parse method are culture-sensitive unless the string to be parsed (which is represented by s in the following table) conforms to the ISO 8601 pattern. The parsing operation uses the formatting information in a DateTimeFormatInfo object that is derived as follows:
If you call | And provider is | Formatting information is derived from |
---|---|---|
Parse(String) | — | The current culture (DateTimeFormatInfo.CurrentInfo property) |
Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) | a DateTimeFormatInfo object | The specified DateTimeFormatInfo object |
Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) | null | The current culture (DateTimeFormatInfo.CurrentInfo property) |
Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) | a CultureInfo object | The CultureInfo.DateTimeFormat property |
Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) | Custom IFormatProvider implementation | The IFormatProvider.GetFormat method |
When formatting information is derived from a DateTimeFormatInfo object, the DateTimeFormatInfo.Calendar property defines the calendar used in the parsing operation.
If you parse a date and time string by using a DateTimeFormatInfo object with customized settings that are different from those of a standard culture, use the ParseExact method instead of the Parse method to improve the chances for a successful conversion. A non-standard date and time string can be complicated and difficult to parse. The Parse method tries to parse a string with several implicit parse patterns, all of which might fail. In contrast, the ParseExact method requires you to explicitly designate one or more exact parse patterns that are likely to succeed. For more information, see the «DateTimeFormatInfo and Dynamic Data» section in the DateTimeFormatInfo topic.
Note that the formatting conventions for a particular culture are dynamic and can be subject to change. This means that parsing operations that depend on the formatting conventions of the default (current) culture or that specify an IFormatProvider object that represents a culture other than the invariant culture can unexpectedly fail if any of the following occurs:
To prevent the difficulties in parsing data and time strings that are associated with changes in cultural data, you can parse date and time strings by using the invariant culture, or you can call the ParseExact or TryParseExact method and specify the exact format of the string to be parsed. If you are serializing and deserializing date and time data, you can either use the formatting conventions of the invariant culture, or you can serialize and deserialize the DateTime value in a binary format.
For more information see the «Dynamic culture data» section in the CultureInfo topic and the «Persisting DateTime values» section in the DateTime topic.
Parsing and style elements
All Parse overloads ignore leading, inner, or trailing white-space characters in the input string (which is represented by s in the following table). The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters («#», U+0023), and can be trailed with one or more NULL characters (U+0000).
In addition, the Parse(String, IFormatProvider, DateTimeStyles) overload has a styles parameter that consists of one or more members of the DateTimeStyles enumeration. This parameter defines how s should be interpreted and how the parse operation should convert s to a date and time. The following table describes the effect of each DateTimeStyles member on the parse operation.
DateTimeStyles member | Effect on conversion | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AdjustToUniversal | Parses s and, if necessary, converts it to UTC, as follows:The return value and DateTime.KindThe DateTime.Parse overloads return a DateTime value whose Kind property includes time zone information. It can indicate that the time is: Generally, the Parse method returns a DateTime object whose Kind property is DateTimeKind.Unspecified. However, the Parse method may also perform time zone conversion and set the value of the Kind property differently, depending on the values of the s and styles parameters:
The following example converts date strings that contain time zone information to the time in the local time zone: You can also preserve the value of a date and time’s Kind property during a formatting and parsing operation by using the DateTimeStyles.RoundtripKind flag. The following example illustrates how the RoundtripKind flag affects the parsing operation on DateTime values that are converted to strings by using the «o», «r», or «u» format specifier. Parse(String)Converts the string representation of a date and time to its DateTime equivalent by using the conventions of the current culture. ParametersA string that contains a date and time to convert. See The string to parse for more information. ReturnsExceptionss does not contain a valid string representation of a date and time. ExamplesThe following example parses the string representation of several date and time values by: Using the default format provider, which provides the formatting conventions of the current culture of the computer used to produce the example output. The output from this example reflects the formatting conventions of the en-US culture. Using the default style value, which is AllowWhiteSpaces. It handles the FormatException exception that is thrown when the method tries to parse the string representation of a date and time by using some other culture’s formatting conventions. It also shows how to successfully parse a date and time value that does not use the formatting conventions of the current culture. RemarksIf s contains time zone information, this method returns a DateTime value whose Kind property is DateTimeKind.Local and converts the date and time in s to local time. Otherwise, it performs no time zone conversion and returns a DateTime value whose Kind property is DateTimeKind.Unspecified. This overload attempts to parse s by using the formatting conventions of the current culture. The current culture is indicated by the CurrentCulture property. To parse a string using the formatting conventions of a specific culture, call the Parse(String, IFormatProvider) or the Parse(String, IFormatProvider, DateTimeStyles) overloads. Convert. To Date Time МетодОпределениеНекоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений. Преобразует заданное значение к значению DateTime. ПерегрузкиПри вызове этого метода всегда возникает исключение InvalidCastException. Преобразует заданное строковое представление даты и времени в эквивалентное значение даты и времени. При вызове этого метода всегда возникает исключение InvalidCastException. Преобразует заданное строковое представление числа в эквивалентное значение даты и времени, учитывая указанные сведения об особенностях форматирования, связанных с языком и региональными параметрами. При вызове этого метода всегда возникает исключение InvalidCastException. Преобразует значение заданного объекта в объект DateTime, используя указанные сведения об особенностях форматирования, связанных с языком и региональными параметрами. При вызове этого метода всегда возникает исключение InvalidCastException. При вызове этого метода всегда возникает исключение InvalidCastException. Преобразует значение указанного объекта в объект DateTime. При вызове этого метода всегда возникает исключение InvalidCastException. При вызове этого метода всегда возникает исключение InvalidCastException. При вызове этого метода всегда возникает исключение InvalidCastException. При вызове этого метода всегда возникает исключение InvalidCastException. При вызове этого метода всегда возникает исключение InvalidCastException. Возвращает заданный объект DateTime; фактическое преобразование не производится. При вызове этого метода всегда возникает исключение InvalidCastException. При вызове этого метода всегда возникает исключение InvalidCastException. При вызове этого метода всегда возникает исключение InvalidCastException. ToDateTime(Single)При вызове этого метода всегда возникает исключение InvalidCastException. ПараметрыЗначение с плавающей запятой одиночной точности, которое нужно преобразовать. Возвращаемое значениеЭто преобразование не поддерживается. Возвращаемое значение отсутствует. ИсключенияЭто преобразование не поддерживается. См. также разделПрименяется кToDateTime(String)Преобразует заданное строковое представление даты и времени в эквивалентное значение даты и времени. ПараметрыСтроковое представление даты и времени. Возвращаемое значениеИсключенияvalue является неправильно отформатированной строкой даты и времени. ПримерыВ следующем примере метод используется ToDateTime для преобразования различных строковых представлений дат и времени в DateTime значения. КомментарииЕсли вы предпочитаете не обрабатывать исключение при сбое преобразования, можно вызвать DateTime.TryParse метод. Он возвращает Boolean значение, указывающее, успешно ли выполнено преобразование или завершилось сбоем. См. также разделПрименяется кToDateTime(UInt16)Этот API несовместим с CLS. При вызове этого метода всегда возникает исключение InvalidCastException. Параметры16-разрядное целое число без знака для преобразования. Возвращаемое значениеЭто преобразование не поддерживается. Возвращаемое значение отсутствует. ИсключенияЭто преобразование не поддерживается. См. также разделПрименяется кToDateTime(String, IFormatProvider)Преобразует заданное строковое представление числа в эквивалентное значение даты и времени, учитывая указанные сведения об особенностях форматирования, связанных с языком и региональными параметрами. ПараметрыСтрока, содержащая дату и время, которые нужно преобразовать. Объект, предоставляющий сведения о форматировании для определенного языка и региональных параметров. Возвращаемое значениеИсключенияvalue является неправильно отформатированной строкой даты и времени. ПримерыВ следующем примере преобразуются строковые представления значений даты с ToDateTime помощью метода с помощью IFormatProvider объекта. КомментарииЕсли вы предпочитаете не обрабатывать исключение при сбое преобразования, можно вызвать DateTime.TryParse метод. Он возвращает Boolean значение, указывающее, успешно ли выполнено преобразование или завершилось сбоем. См. также разделПрименяется кToDateTime(UInt64)Этот API несовместим с CLS. При вызове этого метода всегда возникает исключение InvalidCastException. Параметры64-разрядное целое число без знака для преобразования. Возвращаемое значениеЭто преобразование не поддерживается. Возвращаемое значение отсутствует. ИсключенияЭто преобразование не поддерживается. См. также разделПрименяется кToDateTime(Object, IFormatProvider)Преобразует значение заданного объекта в объект DateTime, используя указанные сведения об особенностях форматирования, связанных с языком и региональными параметрами. ПараметрыОбъект, реализующий интерфейс IConvertible. Объект, предоставляющий сведения о форматировании для определенного языка и региональных параметров. Возвращаемое значениеИсключенияvalue не является допустимым значением даты и времени. value не реализует интерфейс IConvertible. Преобразование не поддерживается. ПримерыВ следующем примере определяется настраиваемый поставщик формата, CustomProvider метод которого GetFormat выводит сообщение в консоль, которую он был вызван, а затем возвращает DateTimeFormatInfo объект языка и региональных параметров, имя которого было передано в качестве параметра конструктору класса. Каждый из этих CustomProvider объектов используется для преобразования элементов в массив объектов в значения даты и времени. Выходные данные указывают, что CustomProvider объект используется в преобразовании только в том случае, если тип value параметра имеет значение String. Источники информации:
|