时间字符串<年月日时分秒毫秒 >转为 时间戳代码
时间: 2023-12-08 20:06:10 浏览: 41
以下是将时间字符串转换为时间戳的 Python 代码:
```
import time
time_str = '2021-09-27 15:30:45.123'
time_format = '%Y-%m-%d %H:%M:%S.%f'
timestamp = int(time.mktime(time.strptime(time_str, time_format)) * 1000 + int(time_str[-3:]))
print(timestamp)
```
请注意,由于时间戳通常以毫秒为单位,因此上面的代码将时间戳乘以 1000 并添加时、分、秒和毫秒的偏移量。
相关问题
java将字符串年月日时分秒转为时间错
可以使用Java中的时间工具类`java.time.LocalDateTime`和`java.time.Instant`来实现将字符串年月日时分秒转为时间戳的功能。具体代码如下:
```java
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String str = "2022-01-01 00:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
long timestamp = dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
System.out.println(timestamp);
}
}
```
其中,首先使用`DateTimeFormatter`将字符串转换为`LocalDateTime`对象,然后调用`toInstant`方法将`LocalDateTime`对象转换为`Instant`对象,并指定时区偏移量为东八区(即北京时间),最后调用`toEpochMilli`方法将时间戳转换为毫秒级别的时间戳。
java将年月日时分秒的字符串转成时间戳
可以使用Java中的SimpleDateFormat类将年月日时分秒的字符串转换为时间戳。具体步骤如下:
1. 创建SimpleDateFormat对象,设置日期格式
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
```
2. 将日期字符串解析为Date对象
```java
String dateStr = "2021-08-25 13:30:00";
Date date = sdf.parse(dateStr);
```
3. 将Date对象转换为时间戳
```java
long timestamp = date.getTime();
```
完整代码示例:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeStampDemo {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = "2021-08-25 13:30:00";
Date date = sdf.parse(dateStr);
long timestamp = date.getTime();
System.out.println(timestamp);
}
}
```
输出结果为:1629880200000,表示时间戳为2021-08-25 13:30:00的毫秒数。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)